I have a django project with 5 different models in it. 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?
-
Is there any dependency among all those date field in 5 models? I mean why not formulate it such that you create a common date field? – Nagaraj Tantri Nov 28 '11 at 04:18
-
@NagarajTantri There's no dependencies between models (every model represent different part of a project). But how exactly i would make common date field? By model inheritance? – nukl Nov 28 '11 at 04:24
-
A somewhat related question about combining querysets: http://stackoverflow.com/questions/431628 – akaihola Nov 28 '11 at 07:16
2 Answers
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. 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. 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. In contrast, iterating over a QuerySet will take advantage of your database to load data and instantiate objects only as you need them.
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, e.g.:
querysets = [cls.objects.filter(date=now) for cls in [Model1, Model2, Model3]]

- 55,314
- 10
- 149
- 165
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.
Thank @nrabinowitz for pointing out my previous error.

- 1,577
- 1
- 10
- 14
-
1I'm confused - PolyModel is Appengine-specific, isn't it? It isn't part of Django, and I don't think the OP could use it here. Your point about inheritance is a good one, though - the relevant Django docs are [available here](https://docs.djangoproject.com/en/1.3/topics/db/models/#multi-table-inheritance). – nrabinowitz Nov 28 '11 at 04:43
-
Ah you're absolutely right. My bad. Django=App-Engine for me, so I overlooked it. Answer's been edited. – SteveShaffer Nov 28 '11 at 04:51