I am trying to update my serializers in my drf project to be shown in a nested way. The two models in question are Image and Gallery, images are related to Galleries.
I tried following https://www.django-rest-framework.org/api-guide/relations/#nested-relationships, but i am not entirely sure why it is not working.
Below is models.py
class Gallery(models.Model):
title = models.CharField(max_length=30)
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True, blank=True)
modified_on = models.DateTimeField(auto_now=True, blank=True)
def __str__(self):
return self.title
class Image(models.Model):
gallery_id = models.ForeignKey(Gallery, on_delete=models.CASCADE)
img = models.ImageField(upload_to='images/')
created_on = models.DateTimeField(auto_now_add=True, blank=True)
serializers.py
class ImageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Image
fields = ["gallery_id", "img", "created_on", "id"]
class GallerySerializer(serializers.HyperlinkedModelSerializer):
image = ImageSerializer(many=True, read_only=True)
def validate(self, data):
# Check if user id is equal object id before creation or if SuperUser
request = self.context.get("request")
if request.user.id != data["author"].id and request.user.is_superuser is not True:
raise ValidationError("Unauthorized User Post")
return data
class Meta:
model = Gallery
fields = ["title", "author", "created_on", "modified_on", "image", "id"]
Expecting outcome would be
[
{
"title": "test_1",
"author": "http://127.0.0.1:8000/api/users/2/",
"created_on": "2019-08-19T09:13:45.107658Z",
"modified_on": "2019-08-19T09:13:45.107731Z",
"image": [
{
"gallery_id": "http://127.0.0.1:8000/api/galleries/24/",
"img": "http://127.0.0.1:8000/media/images/angga-tantama-background-art-minimalism.jpg",
"created_on": "2019-08-20T09:17:31.790901Z",
"id": 6
},
{
"gallery_id": "http://127.0.0.1:8000/api/galleries/24/",
"img": "http://127.0.0.1:8000/media/images/art-vector-background-illustration-minimalism-angga-tantam-2.jpg",
"created_on": "2019-08-20T09:31:40.505035Z",
"id": 7
}
]
"id": 24
},
{
"title": "test_2",
"author": "http://127.0.0.1:8000/api/users/2/",
"created_on": "2019-08-20T09:42:09.448974Z",
"modified_on": "2019-08-20T09:42:09.449042Z",
"id": 27
}
]