0

I would like to select one to many table relation in query set.I have two model.

class Post(models.Model):
    postid = models.AutoField(primary_key=True)

    class Meta:
        db_table = 'post'

class Images(models.Model):
    postid = models.ForeignKey(Post,on_delete=models.CASCADE)
    image = models.ImageField(upload_to=upload_image_to, blank=True)

In list method of Post viewset, I would like to select format like=>

          {
            "postid": 1,
            "images":[
                image:"Image Result"
            ]
          }

Here is Post viewset =>

def list(self, request):
        queryset = self.queryset
        page = self.paginate_queryset(queryset)

        for post in self.queryset:
            img = Images.objects.all().filter(postid=post.postid)

        serializer = PostSerializer(page, many=True)
        return self.get_paginated_response(serializer.data)

How to insert this img result to post?

Loran
  • 772
  • 4
  • 16
  • 38

1 Answers1

1

Take a look at the RelatedField documentation. Something like:

class PostSerializer(serializers.ModelSerializer):
    images = serializers.StringRelatedField(many=True)

    class Meta:
        model = Post
        fields = ['postid', 'images']

This will give you a string representation of the Image, but you can look at other Relationship fields in the documentation to customise the JSON representation of the image.

Doing it like this will likely mean you don't need to override list() in the viewset as well.

Matthew Hegarty
  • 3,791
  • 2
  • 27
  • 42
  • Thank for your answer, I solved this by using a nested relationship.[https://www.django-rest-framework.org/api-guide/relations/#nested-relationships] – Loran May 12 '20 at 16:42