0

I'm working on a real estate app and want the listings to show only the first image of the Listing. Currently it is showing all images.

class Image(models.Model):
    photo = models.ImageField(blank=True, upload_to=get_image_filename)
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE)


class ImageSerializerForListingList(serializers.ModelSerializer):
    photo = serializers.ImageField()

    class Meta:
        model = Image
        fields = ('photo', )


class ListingListSerializer(serializers.HyperlinkedModelSerializer):
    image = ImageSerializerForListingList(many=True, required=False, source='image_set')

    class Meta:
        model = Listing
        fields = ('url', 'address', 'image', )

    def get_first_image(self, obj):
        image = obj.image_set.all().first()
        return ImageSerializerForListingList(image, many=True).data

This is still showing all images,

enter image description here

Any advice on this?

master_j02
  • 377
  • 3
  • 13
  • Just use filter in your view and serialize only one object. Show me your model and view and I'll try to write solution. – Lothric Mar 12 '20 at 01:08

1 Answers1

0

solution

"Although you define the get_first_image method on the ListingListSerializer, you are not using it anywhere.

The methods defined on the serializers only get used implicitly when there is a corresponding SerializerMethodField defined on the serializer."

class ListingListSerializer(serializers.HyperlinkedModelSerializer):
    first_image = serializers.SerializerMethodField()

    class Meta:
        model = Listing
        fields = ('url', 'address', 'first_image', )

    """Much like our web app our listing view should only show one Image"""

    def get_first_image(self, obj):
        image = obj.image_set.first()
        return FirstImageSerializer(image).data
master_j02
  • 377
  • 3
  • 13