django从多个表连接查询集

dan*_*ana 0 django join django-queryset

如果我对多个表有查询,例如:

d = Relations.objects.filter(follow = request.user).filter(date_follow__lt = last_checked)
r = Reply.objects.filter(reply_to = request.user).filter(date_reply__lt = last_checked)
article = New.objects.filter(created_by = request.user)
vote = Vote.objects.filter(voted = article).filter(date__lt = last_checked)
Run Code Online (Sandbox Code Playgroud)

我希望显示按日期排序的所有结果(我的意思是不列出所有回复,然后是所有投票等).不知何故,我想在一个查询集中"加入所有这些结果".有可能吗?

seb*_*piq 9

看起来你需要不同的对象来进行常见操作......

1)在这种情况下,最好在超类中抽象这些属性...我的意思是你可以有一个Event定义一个user字段的类,所有其他的事件类都会对它进行子类化.

class Event(model.Model):
    user = models.ForeignKey(User)
    date = ...

class Reply(Event):
    #additional fields

class Vote(Event):
    #additional fields
Run Code Online (Sandbox Code Playgroud)

然后你就可以做到以下几点

Event.objects.order_by("date") #returns both Reply, Vote and Event
Run Code Online (Sandbox Code Playgroud)

有关模型继承的信息,请查看http://docs.djangoproject.com/en/1.2/topics/db/models/#id5.

2)您还可以拥有一个Event与另一个对象具有通用关系的模型.这对我来说听起来更干净,因为Vote概念上不是"事件".退房:http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1

无论如何,我认为你的问题是设计问题