class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('died', null=True, blank=True)
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'author', 'summary')
class BookAPIListView(ListAPIView):
serializer_class = BookSerializer
queryset = Book.objects.all()
urlpatterns += [
path('api/books/', views.BookAPIListView.as_view(), name='api_books')
]
我正在尝试编写一个API以返回书名,作者和书摘。但是,由于这本书的作者是外键,因此它返回的是id而不是作者的名字。修复它的简单方法是什么?提前致谢。
答案 0 :(得分:0)
您也可以编辑BookSerializer
来序列化Author
,从而将其表示为“ 嵌套”数据。因此,我们首先为Author
模型定义一个序列化器:
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('first_name', 'last_name', 'date_of_birth', 'date_of_birth')
,然后指定此序列化器作为序列化author
模型的Book
字段的方式:
class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = Book
fields = ('title', 'author', 'summary')
有关更多信息,请参见documentation on nested relationships [Django-rest-doc]。