问题
I have many hits by Twavail I have many Twavail for a Twaffic
I would like to sum the number of Hits for a Twaffic, and get an additionel field in Twaffic entries (hits_count), but I have some difficulties.
Here are my models:
class Twaffic(models.Model):
user = models.ForeignKey(User,editable=False)
enchere = models.PositiveIntegerField(default=1)
class Twavail(models.Model):
user = models.ForeignKey(User,editable=False)
twaffic = models.ForeignKey(Twaffic,editable=False,related_name='twavaux')
tweet_id = models.CharField(max_length=20,default=0, editable=False)
class Hit(models.Model):
twavail = models.ForeignKey(Twavail,editable=False,related_name='hits')
date = models.DateTimeField(max_length=140,auto_now=True,default="")
I tried:
twaffics=Twaffic.objects.annotate(hits_count=Sum('twavaux__hits__count')).filter(user=request.user)
But I get the following error:
Cannot resolve keyword 'hits' into field. Choices are: twaffic, user
Is it really impossible to get this informations 2 levels ago? hits is the right related name.. Maybe I missed something?
Thx for your help.
回答1:
Try using this...
hit_count = Hit.objects.filter(twavail__id__in = Twavail.objects.filter(twaffic = twaffic_obj).values_list('id', flat=True)).count()
回答2:
I found the answer:
twaffics=Twaffic.objects.annotate(hits_count=Count('twavaux__hits')).filter(user=request.user)
After having added hits application to my settings.py it works, that was the big point.
来源:https://stackoverflow.com/questions/13013333/django-sum-the-count-of-a-sub-sub-foreign-object