在我的models.py
中,有两种模型:
class Genre(models.Model):
genre_id = models.CharField(max_length=10)
name = models.CharField(max_length=40)
information = models.CharField(max_length=120)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
def __str__(self):
return self.title
它们已序列化:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'author', 'genre')
class GenreSerializer(serializers.ModelSerializer):
class Meta:
model = Genre
fields = ('name', 'information')
为每个创建和ViewSets
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
class GenreViewSet(viewsets.ModelViewSet):
queryset = Genre.objects.all()
serializer_class = GenreSerializer
我想做的是:
POST
端点发送一个books/
请求。发送的数据必须包含现有的类型ID,否则将不会保存到数据库中(默认情况下已经完成)。information
模型接收Genre
作为响应。让我举一个简短的例子:
我正在发送此JSON:
{
"title": "Hercules Poirot",
"author": "Agatha Christie",
"genre": 1
}
我收到的不是这样的重复请求:
{ "genre": "crime story" }
该怎么做?
答案 0 :(得分:0)
您可以做的是在create
内添加自定义BookViewSet
方法,以覆盖return语句。
您可以举例说明在create
(https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L12)中实现的默认CreateModelMixin
方法
答案 1 :(得分:0)
您可以说出嵌套字段将如何工作。像这样:
class GenreSerializer(serializers.ModelSerializer):
class Meta:
model = Genre
fields = ('name', 'information')
class BookSerializer(serializers.ModelSerializer):
genre = GenreSerializer(read_only=True)
class Meta:
model = Book
fields = ('title', 'author', 'genre')