django连接多个表的查询集
如果我对多个表有查询,例如:
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)
并且我想显示按日期排序的所有表的结果(我的意思是不列出所有回复,然后列出所有投票等)。 不知何故,我想在一个查询集中“加入所有这些结果”。 有可能吗?
If I have queries on multiple tables like:
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)
and I want to display the results from all of them ordered by date (I mean not listing all the replies, then all the votes, etc ).
Somehow, I want to 'join all these results', in a single queryset.
Is there possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来你需要不同的对象来进行共同的操作......
1)在这种情况下,最好将这些属性抽象到一个超类中......我的意思是你可以有一个
Event
类它定义了一个user
字段,并且所有其他事件类都会对其进行子类化。然后您就可以执行以下
检查 http:// /docs.djangoproject.com/en/1.2/topics/db/models/#id5 有关模型继承的信息。
2) 您还可以拥有一个与另一个对象具有通用关系的
Event
模型。这对我来说听起来更清晰,因为投票在概念上不是“事件”。签出: http://docs.djangoproject.com/en /dev/ref/contrib/contenttypes/#id1无论如何,我认为你的问题是设计问题
It seems like you need different objects to have common operations ...
1) In this case it might be better to abstract these properties in a super class... I mean that you could have an
Event
class that defines auser
field, and all your other event classes would subclass this.Then you would be able to do the following
Check-out http://docs.djangoproject.com/en/1.2/topics/db/models/#id5 for info on model inheritance.
2) You could also have an
Event
model with a generic relation to another object. This sounds cleaner to me as aVote
is conceptually not an "event". Check-out : http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1Anyway, I think your problem is a matter of design
除了 Sebastien 的建议 2 之外:Django 实际上有一些内置功能,您可以为此“滥用”;对于管理员来说,它已经有一个模型,可以记录用户的操作并通过通用外键关系引用对象,我认为您可以对该模型进行子类化并将其用于您的目的:
您现在可以记录所有通知等。它们与
log_addition(request, object)
一起发生并过滤日志表而不是为了您的目的!如果您还想记录更改/删除等,您可以为此创建一些辅助函数!In addition to to Sebastien's proposal number 2: Django actually has some built-in functionality that you could "abuse" for this; for the admin it has already a model that logs the user's actions and references the objects through a generic foreign key relation, I think you could just sub-class this model and use it for your purposes:
You can now log all your notifications etc. where they happen with with
log_addition(request, object)
and filter the Log table than for your purposes! If you want to log also changes / deletions etc. you can make yourself some helper functions for that!