95๐
Based on your error message and this other question, it seems to me this would fix it:
p = Product.objects.filter(vendornumber='403516006')\
.order_by('vendor__name', '-created').distinct('vendor__name')
That is, it seems that the DISTINCT ON
expression(s) must match the leftmost ORDER BY
expression(s). So by making the column you use in distinct
as the first column in the order_by
, I think it should work.
31๐
Just matching leftmost order_by() arg and distinct() did not work for me, producing the same error (Django 1.8.7 bug or a feature)?
qs.order_by('project').distinct('project')
however it worked when I changed to:
qs.order_by('project__id').distinct('project')
and I do not even have multiple order_by args.
- [Django]-How can I restrict Django's GenericForeignKey to a list of models?
- [Django]-How to have a Python script for a Django app that accesses models without using the manage.py shell?
- [Django]-Using Pylint with Django
28๐
In case you are hoping to use a separate field for distinct and order by another field you can use the below code
from django.db.models import Subquery
Model.objects.filter(
pk__in=Subquery(
Model.objects.all().distinct('foo').values('pk')
)
).order_by('bar')
- [Django]-Django โ {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Django @login_required decorator for a superuser
- [Django]-Chaining multiple filter() in Django, is this a bug?
4๐
I had a similar issue but then with related fields. With just adding the related field in distinct()
, I didnโt get the right results.
I wanted to sort by room__name
keeping the person
(linked to residency
) unique. Repeating the related field as per the below fixed my issue:
.order_by('room__name', 'residency__person', ).distinct('room__name', 'residency__person')
See also these related posts:
- [Django]-Detect mobile, tablet or Desktop on Django
- [Django]-Are sessions needed for python-social-auth
- [Django]-How can I enable CORS on Django REST Framework