django 1.3:使用外键和多对多关系进行值和注释
我得到了这些模型:
from django.db import models
class Feed(models.Model):
readers = models.ManyToManyField('auth.user')
# other fields
class Entry(models.Model):
feed = models.ForeignKey(Feed)
read_by = models.ManyToManyField('auth.user')
# other fields
Feed
实例的所有读者都位于 readers
集中。如果User
读取Entry
,则User
将被添加到read_by
集中。
现在我遇到了以下问题:如何为一个 User
获取每个 Feed
的未读 Entries
的数量 用户阅读?
来自 Feed
方面,以下语句排除了给定 User
读取 Entries
的所有 Feed
Feed.objects.filter(readers=user).values('public_id').annotate(models.Count('entry')).exclude(entry__read_by=user)
:从 Entry
的另一端来看,以下语句不会将 Feeds
和计数分组在一起:
Entry.objects.exclude(read_by=user).filter(feed__readers=user).values('feed').annotate(models.Count('id'))
编辑:
我被要求提供示例数据。因此,请考虑以下设置:
User
U 读取三个 Feed
:FeedOne、FeedTwo、FeedThree。
对于每个Feed
,当前数据库中有五个条目
。 FeedOne 的两个 Entries
已被 User
U 读取。
摘要:
FeedOne
EntryA (read by U)
EntryB (read by U)
EntryC
EntryD
EntryE
FeedTwo
EntryF
EntryG
EntryH
EntryI
EntryJ
FeedThree
EntryK
EntryL
EntryM
EntryN
EntryO
我需要的是每个 Feed 的未读
:Entries
的计数此用户
的
FeedOne: 3
FeedTwo: 5
FeedThree: 5
I got these models:
from django.db import models
class Feed(models.Model):
readers = models.ManyToManyField('auth.user')
# other fields
class Entry(models.Model):
feed = models.ForeignKey(Feed)
read_by = models.ManyToManyField('auth.user')
# other fields
A Feed
instance has all of it's readers in the readers
set. If an User
reads an Entry
, the User
is added to the read_by
set.
Now I'm stuck with the following problem: How can I get for one User
the count of unread Entries
for every Feed
the User
reads?
Coming from the Feed
side, the following statement excluded me all Feeds
with read Entries
for the given User
:
Feed.objects.filter(readers=user).values('public_id').annotate(models.Count('entry')).exclude(entry__read_by=user)
Coming from the other Entry
side, the following statement does not group the Feeds
and the counts together:
Entry.objects.exclude(read_by=user).filter(feed__readers=user).values('feed').annotate(models.Count('id'))
Edit:
I was asked to provide example data. So think of the following setup:
User
U reads three Feeds
: FeedOne, FeedTwo, FeedThree.
For every Feed
there are currently five Entries
in database. Two Entries
of FeedOne are already read by User
U.
Summary:
FeedOne
EntryA (read by U)
EntryB (read by U)
EntryC
EntryD
EntryE
FeedTwo
EntryF
EntryG
EntryH
EntryI
EntryJ
FeedThree
EntryK
EntryL
EntryM
EntryN
EntryO
What I need is the count of the unread Entries
for each Feed
of this User
:
FeedOne: 3
FeedTwo: 5
FeedThree: 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
https://docs .djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses
try this:
https://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses