ZvL
ZvL

Reputation: 803

Django get all, with related models

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!

Upvotes: 0

Views: 294

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20539

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.

Upvotes: 1

Related Questions