user9132502 user9132502 - 7 months ago 123
reST (reStructuredText) Question

Show foreign key in DJANGO REST

My first question here. Glad to be part of this community.
My question: I'm using python3 and the django rest framework to create an API.
I have the following models:

class Game(models.Model):
# id = models.AutoField(primary_key=True)
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
url = models.CharField(max_length=100)
created_at = models.BigIntegerField()
updated_at = models.BigIntegerField()
summary = models.CharField(max_length=2000)
first_release_date = models.BigIntegerField()
category = models.SmallIntegerField()
cover = models.CharField(max_length=100)

def __str__(self):
return self.name


class ReleaseDate(models.Model):
id = models.AutoField(primary_key=True)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
created_at = models.BigIntegerField()
updated_at = models.BigIntegerField()
category = models.SmallIntegerField()
platform = models.SmallIntegerField()
date = models.BigIntegerField()
region = models.SmallIntegerField()
y = models.SmallIntegerField()
m = models.SmallIntegerField()
human = models.CharField(max_length=10)


To create a serializer for the Game and ReleaseDate I'd do:

class ReleaseDateSerializer(serializers.ModelSerializer):
class Meta:
model = ReleaseDate
fields = '__all__'


class GameSerializer(serializers.ModelSerializer):

class Meta:
model = Game
fields = '__all__'


... and this would provide me with:

[
{
"name": "God of war",
"url": "efgsd"
},
{
"name": "Uncharted",
"url": "sgdfd"
},
{
"name": "Fortnight",
"url": "efgsd"
}
]


How would I go about to get this, ie:

[
{
"name": "God of war",
"url": "efgsd"
"release_dates": "[
{..},
{..}
]"
},
{
"name": "Uncharted",
"url": "sgdfd"
"release_dates": "[
{..},
{..}
]"
},
{
"name": "Fortnight",
"url": "efgsd"
"release_dates": "[
{..},
{..}
]"
}
]


Thank you very much!

Answer Source

As described in the drf documentation for nested serializers, you'd have to do something like

Modify your game FK in your ReleaseDate model to include a related_name attribute release_date

class Game(models.Model):
     game = models.ForeignKey(Game, related_name = 'release_date', on_delete = models.CASCADE)

and then update your GameSerializer like so

class GameSerializer(serializers.ModelSerializer):
    release_date = ReleaseDateSerializer(many = True, read_only = True)

    class Meta:
        model = Game
        fields = ('name', 'url', 'release_date', )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download