簡體   English   中英

如何在Django中訪問查詢集的特定字段?

[英]How can I access a specific field of a queryset in Django?

我的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>]>
  1. 如何在沒有其他所有數據的情況下訪問每個對象的兩個額定值(5.0和3.0)?

  2. 能否以我能夠平均數字並返回最終值的方式來完成此操作?

對於1.,您可以使用( 相關文檔 ):

Rating.objects.filter(this_book__title='My Test Book').values('rate')

如果只需要一個平面列表,則可以使用values_list('rate', flat=True)代替values('rate')

對於2( 相關文檔 ):

from django.db.models import Avg

Rating.objects.filter(this_book__title='My Test Book').aggregate(Avg('rate'))

這將返回一個字典,其中的鍵是rate__avg ,其值是評分的平均值。

請參閱多對一字段的以下內容django-從多對一關系中獲取對象集

要訪問評級,您可以使用for循環並訪問各個值,例如

total = 0
for rating in book_titles.book_set.all()
    total += rating.rate

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM