首页 > 解决方案 > 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?

标签: django-modelsdjango-rest-frameworkdjango-serializer

解决方案


你在正确的轨道上!

如果您需要有关相关对象的更多详细信息,则使用一个相关字段进行写入并使用另一个字段读取完整对象是一种好方法。

write_only=True如果您希望该字段仅用于写入,您还可以将标志添加到 slug 字段。但是,当您处于 Browseable API 中的更新路线下时,选中此选项不会提示选定的对象

检查这个答案


推荐阅读