开发者

Django - "last_modified" or "auto_now_add" for an App (or more than one Model?)

开发者 https://www.devze.com 2023-03-18 23:40 出处:网络
I know Django has a feature of last_modified field (models.DateTimeField(auto_now_add=True) ).. but let\'s say I have a certain App, and I want to know when was the last change f开发者_运维知识库or a

I know Django has a feature of last_modified field (models.DateTimeField(auto_now_add=True) )..

but let's say I have a certain App, and I want to know when was the last change f开发者_运维知识库or any of its Model (I don't really care which model was changed, I just want to know when was the latest change for this app..)

do I really have to write a last_modified field for each model (I have 9 of them for the moment...), and then check for each of them which is the latest?

any help will be appreciated :) Thanks


You could create a base class that defines the last_modified field...

class YourBaseClassName(models.Model):
    last_modified = models.DateTimeField(auto_now=True)

and then inherit from that

class AnotherClass(YourBaseClassName):
    another_field = models.CharField(max_length=50)


In The End I made a table for constants for my app (actually I had it before for use of other things). so the Table looks like this:

from django.db import models
from django.db.models.signals import post_save

class Constant(models.Model):
    name = models.CharField(max_length=50)
    value = models.CharField(max_length=50)

and added a consant named "version_date".

Than, I added this code to the bottom of my models.py, to track all changes in all the models in the app.

myapp = models.get_app('myapp')
models2track = models.get_models(myapp)
def update_version(sender, **kwargs):
    for model in models2track:
        post_save.disconnect(update_version, sender=model, dispatch_uid="some_uid"+model._meta.db_table)

    version_date = Constant.objects.get_or_create(id=1,name="version date")[0]
    version_date.value = str(int(time.time()))
    version_date.save()

    for model in models2track:
        post_save.connect(update_version, sender=model, dispatch_uid="some_uid"+model._meta.db_table)

for model in models2track:
    post_save.connect(update_version, sender=model, dispatch_uid="some_uid"+model._meta.db_table)

This way, I don't need to change my DB Schema.. only need to add the code mentioned. thanks all

0

精彩评论

暂无评论...
验证码 换一张
取 消