根据请求类型更改Django REST Framework ModelSerializer中的一个字段? [英] Change a field in a Django REST Framework ModelSerializer based on the request type?
问题描述
考虑这种情况,我有一个书
和作者
模型。
Consider this case where I have a Book
and Author
model.
serializers.py
serializers.py
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = models.Author
fields = ('id', 'name')
class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = models.Book
fields = ('id', 'title', 'author')
viewsets.py
viewsets.py
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
如果我发送一本书的 GET
请求,这很好用。我得到一个包含嵌套序列化器的输出,其中包含书籍详细信息和嵌套作者详细信息,这是我想要的。
This works great if I send a GET
request for a book. I get an output with a nested serializer containing the book details and the nested author details, which is what I want.
但是,当我想要创建/更新一本书时,我必须发送一个 POST
/ PUT
/ PATCH
与作者的嵌套细节,而不是他们的id。我想通过指定一个作者id而不是整个作者对象来创建/更新一个书对象。
However, when I want to create/update a book, I have to send a POST
/PUT
/PATCH
with the nested details of the author instead of just their id. I want to be able to create/update a book object by specifying a author id and not the entire author object.
所以,我的序列化程序看起来像这样一个 GET
请求
So, something where my serializer looks like this for a GET
request
class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = models.Book
fields = ('id', 'title', 'author')
和我的序列化程序看起来像一个 POST
, PUT
, PATCH
请求
and my serializer looks like this for a POST
, PUT
, PATCH
request
class BookSerializer(serializers.ModelSerializer):
author = PrimaryKeyRelatedField(queryset=Author.objects.all())
class Meta:
model = models.Book
fields = ('id', 'title', 'author')
我也不想为每种类型的请求创建两个完全独立的序列化程序。我想修改 BookSerializer
中的作者
字段。
I also do not want to create two entirely separate serializers for each type of request. I'd like to just modify the author
field in the BookSerializer
.
最后,是否有更好的方法来做这件事?
Lastly, is there a better way of doing this entire thing?
推荐答案
多个串行器只会产生越来越多的混乱。
IMHO, multiple serializers are only going to create more and more confusion.
相反,我更喜欢以下解决方案:
Rather I would prefer below solution:
- 不要更改您的视图(保留默认值)
- 在序列化程序中添加.validate()方法;以及其他所需的.create或.update()等。这里,真正的逻辑将在
validate()方法中。根据请求类型,我们将根据我们的序列化程序创建
validated_data dict。
我认为这是最干净的方法。
I think this is the cleanest approach.
在 DRF:允许GET请求中的所有字段,但将POST限制为仅一个字段
这篇关于根据请求类型更改Django REST Framework ModelSerializer中的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!