Reputation: 280
I want to get the numbers of values in Two ManyToMany Field and compain both to one Integer Field by function (def)
class Video(models.Model):
viewers = models.ManyToManyField(Account, related_name='video_views')
viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True)
viewers_count = models.IntegerField('Here I want to get the number of both field')
Upvotes: 0
Views: 133
Reputation: 1062
You many do it without saving sum of count viewers_by_ip
and viewers
into database, actually you have to ways.
Make a property method that will calculate it pet each object:
class Video(models.Model):
@property
def total_viewes_count(self):
return self.viewers.count() + self.viewers_by_ip.count()
Add a annotation to queryset which getting model object for you:
from django.db.models import Count
Video.objects.annotate(
total_viewes_count=Count('viewers')+Count('viewers_by_ip')
).get(pk=<Video's primary key>)
in both cases you may use it in template like that:
{{ video.total_viewes_count }}
Upvotes: 1