【问题标题】:django 1.3: values and annotate with foreign keys and many to many relationshipsdjango 1.3:使用外键和多对多关系进行值和注释
【发布时间】:2012-02-23 21:52:53
【问题描述】:

我有这些模型:

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 集合中。

现在我遇到了以下问题:对于每个FeedUser 读取,我如何获得一个User 的未读Entries 计数?

来自Feed 方面,以下语句将我排除在所有Feeds 之外,并针对给定的User 读取Entries

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'))

编辑:

我被要求提供示例数据。因此,请考虑以下设置:

UserU 读取三个Feeds:FeedOne、FeedTwo、FeedThree。

对于每个Feed,数据库中当前有五个Entries。 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

我需要的是这个User中每个Feed的未读Entries计数:

FeedOne: 3
FeedTwo: 5
FeedThree: 5

【问题讨论】:

  • 你能发布示例数据和预期的查询结果吗?我认为这会让你的问题更容易理解

标签: django django-models many-to-many


【解决方案1】:

试试这个:

feed_qs = user.feed_set.exclude(entry__read_by=user).annotate(unread_count=Count('entry'))
for feed if feed_qs:
    print feed, feed.unread_count

https://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses

【讨论】:

  • 我有一个带有 5 个 Feed 的测试数据库。一位用户是所有提要的读者,但只阅读了其中 1 个提要中的条目。根据您的查询,我只获得了其他 4 个提要的计数,但没有获得已读条目的计数。
猜你喜欢
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多