Django annotate query set with a count on subquery

后端 未结 2 574
星月不相逢
星月不相逢 2021-02-04 06:59

This doesn\'t seem to work in django 1.1 (I believe this will require a subquery, therefore comes the title)

qs.annotate(interest_level= \\
             Count(Q(         


        
2条回答
  •  余生分开走
    2021-02-04 07:28

    If you want to avoid dropping to raw SQL, another way to skin this cat would be to use a model method, which will then give you a new attribute on the model to use in your templates. Untested, but something like this on your Tags model should work:

    class Tag(models.Model):
        itemfk = models.ForeignKey(Item, related_name='tags')
        name = models.CharField(max_length=32)
    
        def get_favetag_count(self):
            """
            Calculate the number of times the current user has favorited a particular tag
            """
    
            favetag_count = FavoritedTag.objects.filter(tag=self,user=request.user).count()
            return favetag_count
    

    Then in your template you can use something like :

    {{tag}} ({{tag.get_favetag_count}})
    

    The downside of this approach is that it could hit the database more if you're in a big loop or something. But in general it works well and gets around the inability of annotate to do queries on related models. And avoids having to use raw SQL.

提交回复
热议问题