【发布时间】:2018-02-02 21:13:38
【问题描述】:
我的 Django 应用中有这些模型:
class Book(models.Model):
title = models.CharField(max_length=50, unique=True)
owner = models.CharField(max_length=30)
price = models.DecimalField(max_digits=5, decimal_places=2, null=True)
book_rating = models.ForeignKey('Rating', null=True)
RATE_CHOICES = zip(range(1,6), range(1,6))
class Rating(models.Model):
user = models.ForeignKey(User)
this_book = models.ForeignKey(Book)
rate = models.DecimalField(max_digits=2, decimal_places=1, choices=RATE_CHOICES)
comment = models.TextField(max_length=4000, null=True)
我正在尝试访问 Book 模型的每个实例的 Ratings。这是我迄今为止在 shell 中尝试过的:
from django.contrib.contenttypes.models import ContentType
>>> ctype = ContentType.objects.get_for_model(Rating)
>>> ctype
<ContentType: rating>
>>> book_titles = ctype.model_class().objects.filter(this_book__title='My Test Book')
>>> book_titles
<QuerySet [<Rating: My Test Book - parrot987 - 3.0>, <Rating: My Test Book - 123@gmail.com - 5.0>]>
如何在没有所有其他数据的情况下访问每个对象(5.0 和 3.0)的两个评级值?
这可以通过我能够平均数字并返回最终值的方式完成吗?
【问题讨论】:
-
你有很多书,每本书都有很多用户评分。正确的?如果是这样,为什么不使用 ManyToMany 字段?然后你可以得到一本书的所有评分并平均费率等
-
标签: python django database django-views django-queryset