当我进行聚合查询时,Django模型管理器没有处理相关对象

2024-07-02 13:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

以下是我的模型:

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的值只有在直接查询模型时才是正确的:

^{pr2}$

你能告诉我它怎么了吗?提前谢谢。在


Tags: 模型truegetbymodelstagqueryclass
1条回答
网友
1楼 · 发布于 2024-07-02 13:54:10

我现在已经知道出了什么问题以及如何解决:)

  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.我应该计数notes而不是users

Count('notes', distinct=True)

相关问题 更多 >