简体   繁体   English

通过几个模型查询

[英]Querying through several models

I have a django project with 5 different models in it. 我有一个django项目,其中有5种不同的模型。 All of them has date field. 他们都有日期字段。 Let's say i want to get all entries from all models with today date. 假设我想获取所有具有今天日期的模型的所有条目。 Of course, i could just filter every model, and put results in one big list, but i believe it's bad. 当然,我可以过滤每个模型,然后将结果放在一个大列表中,但是我认为这很不好。 What would be efficient way to do that? 有什么有效的方法可以做到这一点?

I don't think that it's a bad idea to query each model separately - indeed, from a database perspective, I can't see how you'd be able to do otherwise, as each model will need a separate SQL query. 我认为单独查询每个模型不是一个坏主意-实际上,从数据库角度来看,我看不到您将如何做到这一点,因为每个模型都需要单独的SQL查询。 Even if, as @Nagaraj suggests, you set up a common Date model every other model references, you'd still need to query each model separately. 即使按照@Nagaraj的建议,您在每个其他模型引用中都建立了一个通用的Date模型,您仍然需要分别查询每个模型。 You are probably correct, however, that putting the results into a list is bad practice, unless you actually need to load every object into memory, as explained here : 你可能是正确的,但是,把成果转化为一个列表是不好的做法,除非你确实需要加载的每一个对象到内存中,为解释在这里

Be warned, though, that [evaluating a QuerySet as a list] could have a large memory overhead, because Django will load each element of the list into memory. 请注意,[将QuerySet评估为列表]可能会占用大量内存,因为Django会将列表中的每个元素加载到内存中。 In contrast, iterating over a QuerySet will take advantage of your database to load data and instantiate objects only as you need them. 相反,在QuerySet上进行迭代将仅利用数据库来加载数据并仅在需要时实例化对象。

It's hard to suggest other options without knowing more about your use case. 在不进一步了解用例的情况下,很难建议其他选项。 However, I think I'd probably approach this by making a list or dictionary of QuerySets, which I could then use in my view, eg: 但是,我认为我可能会通过制作QuerySet的列表或字典来实现此目的,然后可以在我的视图中使用它,例如:

querysets = [cls.objects.filter(date=now) for cls in [Model1, Model2, Model3]]

Take a look at using Multiple Inheritance (docs here ) to define those date fields in a class that you can subclass in the classes you want to return in the query. 看一下使用多重继承在此处 ,文档)在类中定义那些日期字段,您可以将其子类化为要在查询中返回的类。

For example: 例如:

class DateStuff(db.Model):
  date = db.DateProperty()

class MyClass1(DateStuff):
  ...

class MyClass2(DateStuff):
  ...

I believe Django will let you query over the DateStuff class, and it'll return objects from MyClass1 and MyClass2. 我相信Django将允许您查询DateStuff类,并且它将返回MyClass1和MyClass2中的对象。

Thank @nrabinowitz for pointing out my previous error. 感谢@nrabinowitz指出我以前的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM