Query field across multiple django models
I want to create a "What's New" section that lists all of the database changes in the last day. I've added an "updated" field to my models:
class Film(models.Model):
.
.
.
updated = models.DateTimeField(auto_now=True)
class Actor(models.Model):
.
.
.
updated = models.DateTimeField(auto_now=True)
Now I want to query across all of my models to get a date-sorted list of the most recent changes. How do I开发者_如何学编程 query the "updated" field across multiple models? Is this the most efficient way to achieve the primary purpose?
What if I wanted to be more specific and list the actual field that was altered within each model?
I don't know of any way to run a select across multiple tables… So, unless you want to use my suggestion below, you'll just have to loop across all 'updatable' models.
However, you might want to consider having an UpdatedItems
model, which might be something like:
class ItemUpdate(m.Model):
when = m.DateTimeField(...)
instance = m.GenericForeignKey(...)
field = m.CharField(...)
old_value = m.CharField(...)
new_value = m.CharField(...)
Then use the post_save
signal to populate it:
form django.db.models.signals import post_save
def handle_post_save(sender, instance, *args, **kwargs):
ItemUpdate(instance=instance, ...).save()
I don't know off the top of my head how to figure out which fields are updated… But I'm sure someone's asked about it on Google.
精彩评论