[Solved] Django MySQL distinct query for getting multiple values

I have a MySQL database unfortunately used with Django 1.4.1.
Distinct function is only working for POSTGRESQL if i get it right.

I have to make a distinct query consist of multiple values while only distinct one,

Like;
This one works for POSTGRE but not with MYSQL,
I get the following error;

DISTINCT ON fields is not supported by this database backend

staff = Staff.objects.order_by('person__full_name').distinct('person__full_name')

Then I tried

staff = Staff.objects.values('person__full_name','staff_job_categories').distinct().order_by('person__full_name')

But I do not get distinct values because i get also the staff job categories. But when I dont contain it I could not get it as array.

Any idea ?

Enquirer: tuna

||
Solution #1:

.distinct([*fields]) only works in PostgresSQL.

From distinct documentation

Here’s the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names.

As stated all fields in a record are checked.

Mostly likely in your case you are getting records with different field values (more likely a case if you are queries multiple tables ManyToMany or ForeignKey relations).

For consolidating as array you can refer your earlier question Django Query distinct values works but i cant use the query result

Respondent: Rohan
Solution #2:
names = Staff.objects.order_by('person__full_name').values('person__full_name').distinct()

will give you distinct full names, and you can do a similar thing to get distinct job categories.

These will give you lists of values, not objects themselves, but if I interpret your question correctly then I think these will give you what you want.

Respondent: solidparallel
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.