0

Problem:

I'm using Django Rest Framework and i want to fetch all models with the relationships included, like this:

TestModel.objects.all()

My model looks like this:

class TestModel(models.Model):
   name = models.CharField(max_length=32)
   related_model = models.ForeignKey(TestRelation)

Problem is, i only get the Primary Keys for related_model but i need the whole related_model!

I'm using the ListCreateAPIView, with the above queryset (TestModel.objects.all()) and the most basic form of the ModelSerializer.

I tried the PrimaryKeyRelatedField but i get the same result..

Thanks!

ZvL
  • 793
  • 2
  • 11
  • 25
  • Found my answer: https://stackoverflow.com/questions/14573102/how-do-i-include-related-model-fields-using-django-rest-framework – ZvL Feb 15 '15 at 15:41

1 Answers1

1

Just create serializer for your related model:

class TestRelationSerializer(serializers.ModelSerializer):

    class Meta:
        meta = TestRelation

and use is as field in TestModelSerializer:

class TestModelSerializer(serializers.ModelSerializer):
    related_model = TestRelationSerializer()

You can also do it other way around, by using TestModelSerializer as field in TestRelationSerializer with many set to true:

class TestRelationSerializer(serializers.ModelSerializer):
    testmodel_set = TestModelSerializer(many=True)

just remember, you can't do both at once due to infinite recursion it makes.

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77