我的项目中有两个模型:Author和Book。每本书都有一个指向作者的外键。我想写一个api来检索一个Author的实例,并显示该特定人员的详细信息。问题是我不知道如何把那个人的书包括在我的API中。
这是我的型号.py:
class Book(models.Model):
title = models.CharField(max_length=150)
rating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),])
summary = models.TextField()
author = models.ForeignKey(Author, null=True, on_delete=models.SET_NULL)
class Author(models.Model):
authorID = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
dateOfBirth = models.DateField(null=True)
nationality = models.CharField(null=True, max_length=255)
这是一种对我不起作用的方法:
# Serializers.py
class AuthorRetrieveSerializer(serializers.ModelSerializer):
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
bookDetails = BookSerializer(read_only=True, many=True)
class Meta:
model = Author
fields = ('name', 'dateOfBirth', 'nationality', 'bookDetails')
# Views.py
class AuthorRetrieveViewSet(RetrieveUpdateDestroyAPIView):
permission_classes = (AllowAny,)
serializer_class = serializers.AuthorRetrieveSerializer
queryset = Author.objects.all()
lookup_field = 'authorID'
def get_queryset(self):
return self.queryset
这段代码成功地检索了作者的详细信息,但没有给我他们的书。
您是否尝试在序列化程序上指定源?
# Serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class AuthorRetrieveSerializer(serializers.ModelSerializer):
bookDetails = BookSerializer(read_only=True, many=True, source="book_set")#correction here
class Meta:
model = Author
fields = ('name', 'dateOfBirth', 'nationality', 'bookDetails')