python - 当我进行聚合查询时,Django 模型管理器无法处理相关对象

标签 python django django-models django-aggregation

我在对多对多相关字段进行聚合查询时遇到问题。

这是我的模型:

class SortedTagManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        orig_query_set = super(SortedTagManager, self).get_query_set()
        # FIXME `used` is wrongly counted
        return orig_query_set.distinct().annotate(
                    used=models.Count('users')).order_by('-used')


class Tag(models.Model):
    content = models.CharField(max_length=32, unique=True)
    creator = models.ForeignKey(User, related_name='tags_i_created')
    users = models.ManyToManyField(User, through='TaggedNote',
                                   related_name='tags_i_used')

    objects_sorted_by_used = SortedTagManager()

class TaggedNote(models.Model):
    """Association table of both (Tag , Note) and (Tag, User)"""
    note = models.ForeignKey(Note) # Note is what's tagged in my app
    tag = models.ForeignKey(Tag)
    tagged_by = models.ForeignKey(User)

    class Meta:
        unique_together = (('note', 'tag'),)

但是,只有直接查询模型时,聚合字段used的值才是正确的:

for t in Tag.objects.all(): print t.used # this works correctly

for t in user.tags_i_used.all(): print t.used #prints n^2 when it should give n

请您告诉我这是怎么回事?提前致谢。

最佳答案

我现在已经弄清楚出了什么问题以及如何修复它:)

  1. 如 Django 文档中所述:

Django interprets the first Manager defined in a class as the "default" Manager, and several parts of Django will use that Manager exclusively for that model.

就我而言,我应该确保 SortedTagManager 是第一个定义的 Manager

2.我应该有 count notes 而不是 users:

Count('notes', distinct=True)

关于python - 当我进行聚合查询时,Django 模型管理器无法处理相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2635587/

相关文章:

python - 如何使用Dask从SQL<连接字符串>中读取数据?

带有线程/处理的 Django 长时间运行的异步任务

python - 在 keras 中制作自定义损失函数

没有 "if __name__ == ' __main_ _':"的 python3.x 多处理循环

python - 从dockerfile中的uvicorn命令和pythonfile运行fastapi和pythonfile有什么区别?

ajax - 在 Django 中使用 Dajaxice 刷新表格

python - 使用帐户身份验证来验证是否已登录

django - 日期输入 : how to show placeholder

python - 密码字段在 Django 管理站点中可见且未加密

database - 如何为多对多关系创建 initial_data Json fixture?