Django - 无法使用Model.objects.all()发送prefetch_related()数据

时间:2017-08-01 12:27:36

标签: django

以下是 views.py

def books(request):
    books = Book.objects.prefetch_related('book_stat_set').all()
    for book in books:
        for book_stat in book.book_stat_set.all():
            book.stats = book_stat # what is wrong here
            pprint(vars(book_stat)) # prints book_stat dict perfectly

    books_serial = serializers.serialize("json", books)
    return HttpResponse(books_serial)  

这是我的 models.py

class Book(models.Model):
    title = models.CharField(max_length=200)
    image = models.FileField(upload_to="mp/", blank=True)

    def __str__(self):
        return self.title

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=150)

    def __str__(self):
        return self.full_name

class Book_stat(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    rating = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('0.00'))
    like = models.BooleanField(default=False)

    def __str__(self):
        return self.book.title + ' by: ' + self.user.profile.full_name  

当我发送json数据时,每个stats对象中没有fields字典,但是pprint完全从views.py

输出到终端

输出

[
  {
     pk: 1,
     model: 'some model',
     fields: {
        # here i want to add stats
     }
  },
  {
     pk: 1,
     model: 'some model',
     fields: {
        # here i want to add stats
     }
  }
]  

还想从响应中删除pkmodel

0 个答案:

没有答案