Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update two models in one serializer in Django Rest Framework?

I have a database schema that has each object of a certain type being stored across two separate tables (one row in each table, different data in each, with a foreign key from one to the other.)

Unfortunately, Django Rest Framework tends to assume that there is a one to one correspondence between serializers and models, which is not true of my case. How should I be approaching this? It seems like the serializer should return the representation of the object which will be the actual HTTP response of the ajax requests, so using two serializers doesn't seem right. I've looked at extending BaseSerializer (which is how I currently plan to implement this if I don't find better solutions), but certain methods take in an instance, which should contain all the data needed to serialize the object, whereas I have two instances relevant.

Any advice would be super appreciated! Thank you.

like image 804
Christopher Shroba Avatar asked Sep 29 '16 23:09

Christopher Shroba


1 Answers

Writable nested representations section might help you.

You have 2 models ModelA and ModelB. Create your first model's serializer

class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        fields = ('fields',..) # 

Then in other model's serializer add the first serializer and override the required methods (like create, update). Something like this:

class ModelBSerializer(serializers.ModelSerializer):
    # add the serializer for the foreignkey model 
    model_a = ModelASerializer()   

    class Meta:
        model = ModelB
        fields = ('fields',..) # 

   def create(self, validated_data):
       modela_data = validated_data.pop('model_a')
       model_b = ModelB.objects.create(**validated_data)
       ModelA.objects.create(model_b=model_b, **modela_data)
       return model_b

   # override update too ..
like image 65
Tiny Instance Avatar answered Sep 21 '22 14:09

Tiny Instance