我的 django 应用程序中有 3 个模型
class Company(models.Model):
name = models.CharField(_("Name"), max_length = 100, blank = True, null = True)
address = models.CharField(_("Address"), max_length = 300, blank = True, null = True)
class WebSite(models.Model):
WEBSITE_TYPE_CHOICES = (
('Google+', 'Google+'),
('Facebook', 'Facebook'),
('Orkut', 'Orkut'),
)
user = models.ForeignKey(User)
website = models.URLField(blank = True, null = True)
website_type = models.CharField(max_length = 15, choices = WEBSITE_TYPE_CHOICES, default = 'Google+')
company = models.ForeignKey(Company, null=True, blank=True)
class Review(models.Model):
rating = models.FloatField(blank = True, null = True)
review = models.TextField(blank = True, null = True)
company = models.ForeignKey(Company, null=True, blank=True)
website = models.ForeignKey(Website, null=True, blank=True)
我想显示我的数据,例如
A公司:
- 谷歌 - 5 条评论,平均 3.4
- Orkut - 9 条评论,平均 4.1
- Facebook - 12 条评论,平均 4.3
- 其他 - 2 条评论,平均 2
B公司:
- Google - 2 条评论,平均 3 条
- Facebook - 5 条评论,平均 4 条
为此我做了
final_list = company_list = []
websites = Website.objects.select_related().filter(user = user)
for website in websites:
company = website.company
if company is not None and company not in company_list:
company_list.append(brand)
company_websites = websites.filter(company = company)
info = []
for company_website in company_websites:
company_type = company_website.website_type
reviews = Review.objects.filter(company = company, website = company_website)
no_of_reviews = len(reviews)
average = reviews.aggregate(Avg('rating'))
info.append({"type": company_type, "no_of_reviews": no_of_reviews,
"average": average['rating__avg']})
final_list.append({"company": company.name, "stats": info})
代码有2个问题
- 它浪费了大量的计算
- 它还以某种方式在 final_list 中附加了空列表(BUGGY)
仅供参考:我相信 .annotate() 可以使用,但我不明白如何基于列使用它,在我的情况下是 (company__name)