I have the following model structure:
game | id | name | description | |:-- |:---- |:----------- |
platform | id | name | |:-- |:---- |
game_detail | id | release_date | |:-- |:------------ |
game_platform | id | game_id | platform_id | game_detail_id | |:-- |:------- |:----------- |:-------------- |
game_platform table is the junction table and in which the game_detail_id is foreign key of the game_detail table. Following is the models.py file:
class Game(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
genre = models.ForeignKey(Genre, related_name="games", on_delete=models.CASCADE)
platforms = models.ManyToManyField(
"Platform", related_name="games", through="GamePlatform"
)
class Platform(models.Model):
name = models.CharField(max_length=50)
class GameDetail(models.Model):
release_date = models.DateField()
class GamePlatform(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
game_detail = models.ForeignKey(GameDetail, on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["game", "platform"], name="unique_game_platform"
)
]
How do I serialize in serializers.py and write the logic in modelviewset so that I can get something like this as the game api response:
[
{
"id": 33,
"name": "Crysis Remastered",
"description": "",
"genre": {
"id": 1,
"name": "Fps"
},
"platforms": [
{
"id": 1,
"name": "PS5",
"game_detail": {
"release_date": "2020-11-03"
}
},
{
"id": 2,
"name": "PC",
"game_detail": {
"release_date": "2020-11-13"
}
}
]
}
]
The below code will give you the exact response.
models.py
views.py
serializers.py