多个django模型中的查询字段 [英] 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.
但是,您可能需要考虑使用 UpdatedItems
模型,可能类似于:
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(...)
然后使用 post_save
信号来填充它:
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()
我不知道我的头顶如何弄清楚哪些字段已更新...但我确信有人在Google上询问。
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.
这篇关于多个django模型中的查询字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!