【问题标题】:How to sum up numbers for a foreign key model in djnago如何在 django 中总结外键模型的数字
【发布时间】:2021-11-19 18:50:37
【问题描述】:

我想总结一下登录用户获得奖励的总票数。一个奖项有多个类别和多个提名,我想做的是显示与该奖项相关的所有提名的总票数

model.py

class Award(models.Model):
    admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='award_images')
    slug = models.SlugField(max_length=150)
    about_the_award = models.TextField(blank=True, null=True)
    price = models.CharField(max_length=20, choices=PRICE, default='0.5')
    amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2)
    date = models.DateTimeField(auto_now_add=True)

class Category(models.Model):
    award = models.ForeignKey(Award, on_delete=models.CASCADE)
    category = models.CharField(max_length=100,)
    slug = models.SlugField(max_length=150)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.category


class Nomination(models.Model):
    fullname = models.CharField(max_length=120)
    mominee_ID = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='nominations_images')
    slug = models.SlugField(max_length=150)
    votes = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)


View.py

@method_decorator([login_required], name='dispatch')
class DashboardView(TemplateView):
    template_name = 'admin/Dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_awards'] = Award.objects.filter(Admin=self.request.user).order_by('-date')
        context['number_of_votes'] = Award.objects.filter(Admin=self.request.user, self.catgory.nomination).annotate(Sum('amount'))
        return context



【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:
    from django.db.models import Sum
    
    total_votes = Nomination.objects.filter(category__award=your_award).aggregate(total_votes=Sum('votes'))['total_votes']
    

    注意:字段名称最好以小写字母开头。

    【讨论】:

    • 你应该奖励什么your_award maean。你能进一步解释一下吗?
    • 这是您想要的奖金。你必须自己得到它。
    • 请我将我的模型编辑为小写字母。请编辑您的答案以匹配,以便我可以尝试找出答案。我仍然没有得到结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2019-02-06
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多