rohittk239 rohittk239 - 5 months ago 28
JSON Question

Left Outer Join 2 models and return query in JSON

I am using DRF to serialize and have the api endpoints to display json data.

I have 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)

these are my serializer classes -

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)

will return data with field_fk as a nested dictionary. What i want to is to return other fields of
that arent foreign key to
and append it the final rendered result of
How do i go about this?


If I understand well, you want concatenate the results of FooOneSerailizer and all fields of FooTwoSerializer. You can do so by overriding to_represetation() method.

class FooTwoSerializer(serializers.ModelSerializer): 

     class Meta:
         model = FooTwo
         fields = (field_d, field_e)

     def to_representation(self, instance):
         # get OrderedDict with original fields
         response = super(FooTwoSerializer, self).to_representation(instance)
         # get OrderedDict with foreign foo_one data
         foo_one = FooOneSerializer(instance.field_fk).data
         # set this fields to original data
         for key in foo_one:
             response[key] = foo_one[key]
         return response