开发者

Django model manager didn't work with related object when I do aggregated query

开发者 https://www.devze.com 2022-12-27 07:47 出处:网络
I\'m having trouble doing an aggregation query on a many-to-many related field. Here are my models: class SortedTagManager(models.Manager):

I'm having trouble doing an aggregation query on a many-to-many related field.

Here are my models:

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')).o开发者_如何学运维rder_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'),)

However, the value of the aggregated field used is only correct when the model is queried directly:

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

Would you please tell me what's wrong with it? Thanks in advance.


I have figured out what's wrong and how to fix it now :)

  1. As stated in the Django doc:

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.

In my case, I should make sure that SortedTagManager is the first Manager defined.

2.I should have count notes instead of users:

Count('notes', distinct=True)
0

精彩评论

暂无评论...
验证码 换一张
取 消