[Django]-DRF how can I return only the first serialized object to the view?

2👍

As I am not quite sure how your model is and which the first photo you would like to present(e.g. latest uploaded, first uploaded, latest id). I will use a generic example to explain the solution.

Try serializers.SerializerMethodField() to custom the field which you want to present the latest one.

Suppose there is a list of groups in a user model and you would like to present the latest group id in the user’s detail.

Here is an example:

class UserSerializer(serializers.ModelSerializer):
    latest_group_id = serializers.SerializerMethodField()

    def get_latest_group_id(self, obj):
        return Group.objects.filter(user=obj).latest('id').id

Since you would like to present photo url rather than id, here is the pseudo code.

class UserProfileSerializer(serializers.ModelSerializer):
    latest_image = serializers.SerializerMethodField()

    def get_latest_image(self, obj):
        latest_image = Image.objects.filter(user=obj).latest('id')
        latest_image_serializer = ImageSerializerForListingDetail(latest_image)
        # Deal with edge cases, e.g. latest_image_serializer is not valid
        return latest_image_serializer.data

1👍

You can pass only first item to your serializer:

def get_queryset(self):
    return  Listing.objects.all().order_by('id').first() if self.action == 'retrieve' else Listing.objects.all().order_by('id')

Leave a comment