2011-08-13 40 views
0

我有三个模型,其中有一些共同但不是确切的领域,从单个视图前。回家我检索这样在不同的模型Django视图中的复杂查询

interviews = Interviews.objects.all().order_by('pub_date')[:3] 
publications = Publications.objects.all().order_by('pub_date')[:3] 
published = Published.objects.all().order_by('pub_date')[:3] 

从主页视图我希望他们能够在模板中显示的命令,所有与这些模型相关的最新/新项目将在顶部。

一样,如果进入面试10是最近在这些所有车型进入,那么这将是第一次,那么如果一个公布第二是最近这将是第二次...等.etc

任何一个可以告诉我该怎么做?

回答

0

根据您的其他要求,将它们制作为包含常见元素的常见超类的子版本可能是一个好主意。

这很难说,如果它是有效的,但如果你这样做,你可以通过调用

SuperClass.objects.all().order_by('-pub_date')[:9] 

将呈现什么样sublcass他们是9个第一对象regerdless单独或一起查询不同类型的对象。当然假设超类被命名为SuperClass。当然这并不能保证每个模型都有3个。

解决这个问题的另一个简单方法 - 虽然承认不使用查询,但仅仅是对列表进行排序。

entries = sorted(list(interviews) + list(publications) + list(published), key=lambda x: x.pub_date, reverse=True) 

应该工作 - 基本上把它们变成列表并整理它们。

+0

有什么办法,我能得到像面试子类的名字,所以我可以作为一个类别名称打印 – themunna

+0

[模型inherticance在文档](https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance):要从超类对象中获得一个子类,你可以使用entry.interview, entry.publication或entry.published来获取每个相应的子类对象。如果是采访,则另外两个未设置。 – niklasdstrom

+0

有点用过这个解决方案,但没有使用超类 – themunna

0

一种可能的方式是使用lambda对数据进行排序,但成本hiher因为你这样做是为了蟒蛇,不DBMS ...

lst = [] 
lst.extend(list(Interviews.objects.order_by('pub_date')[:10])) 
lst.extend(list(Publications.objects.order_by('pub_date')[:10])) 
lst.extend(list(Published.objects.order_by('pub_date')[:10])) 
# take 10 records for each, since you could not know how many records will be picked from which table 
# now order them... 
lst.sort(lambda x, y: cmp(x.pub_date, y.pub_date)) 
# and reverse the order, so newset is the first... 
lst.reverse() 

这会给你一个列表对象的有序PY PUB_DATE,这样你就可以切片最终名单得到任何数量的你想记录...

lst = lst[:10]