1👍
✅
You can use the StringAgg
function to get the distinct uuids and then leverage you serializer to split the string and convert it to list of uuids.
class InterestStatusViewset(viewsets.ModelViewSet):
queryset = InterestStatus.objects.all()
serializer_class = InterestStatusSerializer
def get_queryset(self):
qs = super().get_queryset()
qs = qs.annotate(
annotated_interested_uids=StringAgg('interested__account__uuid',',',distinct=True),
annotated_not_interested_uids=StringAgg('not_interested__account__uuid',',',distinct=True),
)
return qs
Serializer can be modified as below to get the required output using SerializerMethodField
class InterestStatusSerializer(serializers.ModelSerializer):
interested_users_uids = serializers.SerializerMethodField()
not_interested_users_uids = serializers.SerializerMethodField()
class Meta:
model = InterestStatus
fields = [
'name',
'interested_users_uids',
'not_interested_users_uids',
]
def get_interested_users_uids(self, obj):
uuids = []
if obj.get('annotated_interested_uids'):
uuids = obj.get('annotated_interested_uids').split(',')
return uuids
def get_not_interested_users_uids(self, obj):
uuids = []
if obj.get('annotated_not_interested_uids'):
uuids = obj.get('annotated_not_interested_uids').split(',')
return uuids
Source:stackexchange.com