以下是 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
}
}
]
还想从响应中删除pk
和model