Django queryset注释来自另一个模型的计算值



我在层次结构中有4个模型:分析、书籍、类别和出版商。在我的应用程序中,你可以分析书籍。书籍属于可以查看该类别中所有书籍的平均分析评级的类别。这个平均评级(我称之为avg catg评级(没有存储在dB中,而是在视图中计算的。

我的问题是:如何获得出版商在单个出版商视图中对每个类别的平均类别评级?换句话说,我如何在每个类别上注释平均catg评级,以便在出版商的页面上显示所有评级?

那么,我是否会像这个问题一样迭代使用类别?如果是,请给我一个建议,因为我真的不知道该怎么做。我也按照这个家伙的建议尝试了groupby,但我只能得到书籍实例的数量,我无法准确地注释平均catg评级。

澄清:

型号.py:

class Analysis: 
title = models.CharField
content_rating_1 = models.IntegerField(blank=True,
null=True, default="0")
content_rating_1_comment = models.TextField(max_length=300, blank=True,
null=True)
source_rating_1 = models.IntegerField(blank=True,
null=True, default="0")
source_rating_1_comment = models.TextField(max_length=300, blank=True,
null=True)
book = models.ForeignKey
class Book:
publication_date = models.DateField(default=datetime.date.today)
slug = models.SlugField(allow_unicode=True, unique=False, max_length=160)
category = models.ForeignKey
class Category:
title = models.CharField(max_length=150, unique=False, blank=False)
sub_title = models.CharField(max_length=100, blank=True, null=True)
publisher = models.ForeignKey

类发布者:title=型号。CharField(最大长度=150,唯一=错误,空白=错误(

publisher/views.py:

class ViewPublisher:
def get_context_data(self, **kwargs):
category_qs = Category.objects.filter(publisher__pk=self.kwargs['pk'])
avg-catg-rating = Books.objects.annotate(long complex queryset that uses values from the analysis model)
context = super(ViewPublisher, self).get_context_data(**kwargs)
context['categories'] = category_qs
context['category_stats'] = Books.objects.filter(category__pk__in=category_qs)
.annotate(.....and now what???)

我放弃了对在视图中做所有事情的痴迷。

解决方案是在模型中创建一个可以在模板中调用的方法。在我的案例中,我在Category/models.py中创建了一个方法:

class Category:
title = models.CharField(max_length=150, unique=False, blank=False)
sub_title = models.CharField(max_length=100, blank=True, null=True)
publisher = models.ForeignKey
def sum_catg_avg_rating(self):
scar = self.books.annotate(avg-catg-rating=(annotate the AVG calculations from the 
analysis))
return scar

然后将类别包含在发布者的上下文中:

class ViewPublisher:
def get_context_data(self, **kwargs):
category_qs = Category.objects.filter(publisher__pk=self.kwargs['pk'])
context = super(ViewPublisher, self).get_context_data(**kwargs)
context['categories'] = category_qs
return context

现在,我可以在模板中称之为:

{% for catg in categories %}
<h5>{{ catg.title }}</h5>
<p> RATING:<i>{{ catg.sum_catg_avg_rating.avg-catg-rating }}</i></p>

最新更新