rohittk239 rohittk239 - 6 months ago 30
JSON Question

Serializing 2 tables using Django Rest Framework

I need to Serialize 2 table to one

object, i have worked with DRF and know how to go about serializing a single model to
. These are the 2 models -

class FooOne(models.Model):
field_a = models.CharField(max_length=255, null=False)
field_b = models.CharField(max_length=255, null=False)
field_c = models.CharField(max_length=255, null=False)

class FooTwo(models.Model):
field_fk = models.ForeignKey(FooOne)
field_d = models.CharField(max_length=255, null=False)
field_e = models.CharField(max_length=255, null=False)

How do i go about achieving this.


If you want do it using nested representation.

class FooOneSerializer(serializers.ModelSerializer): 
    class Meta:
        model = FooOne
        fields = (field_a, field_b, field_c)

class FooTwoSerializer(serializers.ModelSerializer): 
    field_fk = FooOneSerializer()
    class Meta:
        model = FooTwo
        fields = (field_fk, field_d, field_e)

If you want just return everything in a non-nested representation

from rest_framework.renderers import JSONRenderer
data = FooOneSerializer(instance=foo_one_instance).data
json_data = JSONRenderer().render(data)