Home > Back-end >  How to make dynamic field serializer in Django RestFramework
How to make dynamic field serializer in Django RestFramework

Time:03-21

I want to add Dynamic Field Array serializer in my drf project:

My get response looks something like this:

{
    "title": "some",
    "created_at": "2022-03-06T15:59:52.684469Z",
    "fields": [
        {
            "id": 1,
            "title": "Some title?",
            "parent_field": 1
        },
        {
            "id": 2,
            "title": "Yet another fields",
            "parent_field": 1
        }
    ]
}

This is the item detail serializer, and fields is another model serializer. I achieved this by using this code:


class AnotherFieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnotherModel
        fields = "__all__"


class FirstSerializer(serializers.ModelSerializer):
    fields = serializers.SerializerMethodField()

    class Meta:
        model = FirstModel
        fields = "__all__"

    def get_fields(self, obj):
        serializer_context = {'request': self.context.get('request')}

        children = obj.fields
        if not children.exists():
            return None
        serializered_children = FirstSerializer(
            children,
            many=True,
            context=serializer_context
        )
        return serializered_children.data

This works only for GET requests I want this to also work with POST and PUT requests. So, imagine I want to add/edit an item into my model FIRST model and add fields associated with it by just sending this JSON:

{
    "title": "some",
    "created_at": "2022-03-06T15:59:52.684469Z",
    "fields": [
        {
            "id": 1,
            "title": "Some title?",
        },
        {
            "id": 2,
            "title": "Yet another fields",
        }
    ]
}

I know I can get fields from the response and loop through each item to create an instance of Another Model but fields validation will be much harder I think. But if there's more of a drf of doing this thing then it would be great. Also, I have no problem with making another serializer just for POST and PUT requests.

I hope my English was understandable.

CodePudding user response:

You can create a new serializer for validation. To validate multiple items you can do the following,

class PostSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=200)
    created_at = serializers.DateTimeField()
    fields = FirstSerializer(many=True) # your model serializer for the FirstModel 

Ref : https://www.django-rest-framework.org/api-guide/serializers/#listserializer

  • Related