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')
- [Django]-What's the best way to handle different forms from a single page in Django?
- [Django]-Using Django Admin for a custom database solution
- [Django]-Registration form with profile's field
- [Django]-Django.db.utils.IntegrityError: 1452 'Cannot add or update a child row: a foreign key constraint fails
Source:stackexchange.com