【问题标题】:Retrieving Django model value based on another model基于另一个模型检索 Django 模型值
【发布时间】:2021-06-27 10:52:42
【问题描述】:

我一直在关注 youtube 的 django 数据库模型查询,但尝试在不同的上下文中进行操作,以查看我是否理解模型概念,而不仅仅是盲目跟随(结果我根本不理解)。

我试图根据标签名称检索模型中的“视图”值。 我设法拉出单个项目,但我不知道如何根据标签名称检索查看次数。

表格看起来与此类似:

title author body views tags
title a author a blog post a 10 apple, orange, pear
title b author a blog post b 100 banana, orange
title c author a blog post c 50 banana, pear, apple, orange
title d author a blog post d 1 grape

我希望检索的值是标签关联的视图的总和,像这样 标签|计数 --|-- 苹果|60 橙色|160 香蕉|150 葡萄|1 梨|51

这是当前模型

class Tag(models.Model):
    name = models.CharField(max_length=100, null=True)

    def __str__(self):
        return f'{self.name}'


class Blog(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    views = models.IntegerField(default=0)
    tags = models.ManyToManyField(Tag)

    class Meta:
        verbose_name_plural = "Blogs"

    def __str__(self):
        return f'{self.title} | {self.author} | {self.date_created}'

通过在 shell 中运行a = Blog.objects.all(),我可以通过索引 (a[0].views) 来检索视图,但这仅返回特定博客的视图,我如何根据与博客关联的标签返回视图计数?

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    您需要使用Sum function [Django docs] 对相关Blog 实例的views 求和。您可以通过传递默认的相关查询名称 (<model_name_in_lowercase>) 以及用于遍历关系的 __ 来执行此操作,即 blog__viewsSum

    from django.db.models import Sum
    
    
    tags = Tag.objects.annotate(view_sum=Sum('blog__views'))
    
    for tag in tags:
        print(tag.name, tag.view_sum)
    

    【讨论】:

    • 很好,工作。但在另一种情况下,如果我要拉回不是 int/float 的对象不能求和,我该如何处理?
    猜你喜欢
    • 2018-04-15
    • 2020-06-23
    • 2021-10-09
    • 2015-09-26
    • 2021-12-29
    • 1970-01-01
    • 2012-04-21
    • 2011-05-21
    • 2011-07-01
    相关资源
    最近更新 更多