'Distinct not working in DRF sqlite database
Distinct not working.I am using sqlite in backend
class getPatient(generics.ListAPIView):
def list(self, request):
queryset = Patient.objects.all().distinct()
serializer = PatientSerializer(queryset, many=True)
return Response({'patient': serializer.data})
I tried :
queryset = Patient.objects.distinct("name").all()
queryset = Patient.objects.values('name').distinct()
queryset = Patient.objects.all().distinct()
Nothing worked
Solution 1:[1]
I think it is not possible to use order_by and distinct in sqlite database together since in documentation here it is mentioned for example that those works only in PostgreSQL.
Solution 2:[2]
I have to mention that backend sqlite doesn't support distinct. Consider changing for postgresql as the most supported for django backends.
First you have to order objects by the field if you want to distinct. I have included you the documentation and example.
By default, a QuerySet will not eliminate duplicate rows. In practice, this is rarely a problem, because simple queries such as Blog.objects.all() don’t introduce the possibility of duplicate result rows.
Try out, by putting one of your model field. ex. "name".
class getPatient(generics.ListAPIView):
def list(self, request):
queryset = Patient.objects.order_by('name_field').distinct('name_field')
serializer = PatientSerializer(queryset, many=True)
return Response({'patient': serializer.data})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | darth vader |
| Solution 2 |

