I'm very new to both Django and the Django Rest Framework, and I'm struggling with building up a particular JSON response. I have two models, like so:
class Artist(models.model):
artist_id = models.CharField(
max_length=256,
primary_key=True,
)
name = models.CharField(
max_length=256,
null=False,
blank=False,
)
birthplace = models.CharField(
max_length=256,
null=False,
blank=False,
)
class Album(models.Model):
artist = models.ForeignKey(
Artist,
on_delete=models.DO_NOTHING,
db_constraint=False,
null=True,
)
name = models.CharField(
max_length=256,
null=False,
blank=False,
)
label = models.CharField(
max_length=256,
null=False,
blank=False,
)
I'm trying to build a JSON response that looks like this, where the albums are nested inside the artist:
{
"artist_id": "A123",
"name": "Bob Dylan",
"birtplace": "Duluth, Minnesota",
"albums": [
{
"id": 123,
"name": "Bob Dylan",
"label": "Columbia"
},
{
"id": 123,
"name": "The Freewheelin' Bob Dylan",
"label": "Columbia"
}
]
}
Is this even possible? I was looking into select_related, but that doesn't seem to work as I feel like I need to 'hit' the Artist table first, and there is no relationship defined in the direction of Artist to Album.
Any help would be greatly appreciated.