【发布时间】:2018-12-10 23:38:48
【问题描述】:
我在层次结构中有 4 个模型:分析、书籍、类别和出版商。在我的应用程序中,您分析书籍。这些书籍属于类别,您可以在其中查看该类别中所有书籍的平均分析评级。这个平均评分(我称之为 avg-catg-rating)不存储在 dB 中,而是在视图中计算。
这是我的问题:如何将发布商拥有的每个类别的平均类别评分显示到单个发布商视图中?换句话说,我如何将 avg-catg-rating 注释到每个类别上,以便我可以在发布者的页面上显示所有这些?
那么我是否会像question 这样使用类别进行迭代?如果是,请提供有关如何操作的提示,因为我不确定如何去做。我还按照this chap 的建议尝试了 groupby,但我只能获得书籍实例的数量,我无法准确地注释 avg-catg-rating。
澄清一下:
Models.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
类发布者: 标题 = models.CharField(max_length=150, unique=False, blank=False)
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???)
【问题讨论】:
-
你能上传你的模型更多细节吗?
-
感谢您的回复。我在模型中添加了更多字段,希望对您有所帮助。
标签: django django-views