Answer the question
In order to leave comments, you need to log in
How to get sum of fields of Django objects?
There are User and Post models. A user can create a bunch of posts, these posts have a number of likes. How to get the sum of likes from this user from all posts without queriset cycles?
user:
class User(models.Model):
django_user = models.OneToOneField(
DjangoUser, on_delete=models.CASCADE, related_name='user')
name = models.CharField(verbose_name='Имя', max_length=100)
surname = models.CharField(
verbose_name='Фамилия', max_length=100)
phone = models.CharField(
verbose_name='Телефон', blank=True, max_length=100)
save_date = models.DateTimeField(
verbose_name="Дата последнего сохранения", default=now)
def __str__(self):
return self.name + ' ' + self.surname
def get_like_total(self):
.....
class Post(models.Model):
active = models.BooleanField(verbose_name='Активность', default=True)
user = models.ForeignKey(
'User', verbose_name='Пользователь',
null=True, related_name='posts', on_delete=models.CASCADE)
title = models.CharField(
verbose_name='Заголовок', null=True, max_length=200)
category = models.ForeignKey(
'Category', verbose_name='Категория', null=True,
related_name='posts', on_delete=models.SET_NULL)
edit_date = models.DateTimeField(
verbose_name="Дата редактирования", default=now)
class PostLikes(models.Model):
user = models.ForeignKey(
'User', verbose_name="Пользователь",
on_delete=models.CASCADE, related_name="likes")
post = models.ForeignKey(
'Post', verbose_name="Пост",
on_delete=models.CASCADE, related_name="likes")
Answer the question
In order to leave comments, you need to log in
likes = user.posts.all().aggregate(Count('likes'))['likes__count']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question