django-models - Django REST Framework: slug or serializer
问题描述
I am using Django Rest Framework for a project and I have a nested serializer like this:
class TopSerializer(serializers.ModelSerializer):
contact = (something goes here)
email = (something goes here)
For POST, PATCH, PUT, DELETE I want to specify these values with a slug. Suppose each class (Contact, Email) has a member called resource_id
and that is my slug. For these methods I could use:
class TopSerializer(serializers.ModelSerializer):
contact = serializers.SlugRelatedField(read_only=False, slug_field='resource_id')
email = serializers.SlugRelatedField(read_only=False, slug_field='resource_id')
However, for GET I want to return the embedded objects too, so I could use:
class TopSerializer(serializers.ModelSerializer):
contact = ContactSerializer(read_only=True)
email = EmailSerializers(read_only=True)
So how do I specify in my serializer that contact
can be either a slug or a serialized object? Is there a way to do this with just one serializer or must I have two different serializers and use the request.method
in the view to select which serializer I use?
Or, should I use something like this:
class TopSerializer(serializers.ModelSerializer):
contact = ContactSerializer(read_only=True)
email = EmailSerializers(read_only=True)
contact_rid = serializers.SlugRelatedField(read_only=False,slug_field=resource_id,queryset=models.Contact.objects.all())
email_rid = serializers.SlugRelatedField(read_only=False,slug_field=resource_id,queryset=models.Email.objects.all())
This way I can use contact_rid
and email_rid
for POST/PATCH/PUT/DELETE and get contact and email fields back in GET.
Am I on the right track? Other suggestions?
解决方案
你在正确的轨道上!
如果您需要有关相关对象的更多详细信息,则使用一个相关字段进行写入并使用另一个字段读取完整对象是一种好方法。
write_only=True
如果您希望该字段仅用于写入,您还可以将标志添加到 slug 字段。但是,当您处于 Browseable API 中的更新路线下时,选中此选项不会提示选定的对象
检查这个答案
推荐阅读
- neo4j - 您如何找到具有恰好 N 个单一类型关系的所有节点?
- android - 尝试安装应用程序 android studio 时 gradle 缓存出错
- python - 替换多索引数据框中的特定值
- c# - 语言总是英文 asp.net core 3.1
- amazon-web-services - 为使用 AWS Fargate 运行的任务分配动态 IP
- amazon-web-services - 我想知道如何使用 aws cli 检查 DatabaseConnections。?
- javascript - 在 JavaScript 中调用类内部的方法
- javascript - 检查数字是否为回文的Javascript函数
- sql - 如何计算重复值的小时数
- javascript - Deviceorientaion 事件在 Android 上的 Chrome 上不起作用