简体   繁体   中英

How can I get the distinct values of queryset?

I have this query such as

query1 = A.objects.filter(a=a).values('color__red')

And the debugger told me that :

<QuerySet [{'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}]>

I would like to count the number of distinct values of color__red (in my case it is one because color__red = 'yes' but sometimes it can be 2)

I know in the case of an arrays I have to do a len(list(set(array))) but I don't achieve to get the value in the case of queryset.

Could you help me please ?

Thank you !

You can add .distinct() [Django-doc] to the queryset:

query1 = A.objects.filter(a=a).values('color__red').distinct()

In case you want to count the number of distinct objects, you can use .count() [Django-doc] :

n_colors = A.objects.filter(a = a).values('color__red').distinct().count()

You can also define an .aggregate(..) [Django-doc] here, and work with a Count expression [Django-doc] here:

n_colors = A.objects.filter(a=a).aggregate(n_colors = Count('color__red', distinct=True))['n_colors']

The uniqueness filter will then be performed on the database level. So Django will construct a query like:

SELECT DISTINCT app_color.red
FROM app_a
LEFT OUTER JOIN app_color ON app_color.a_id = a.app_a.id
WHERE app_a.a = a

and for the .count() query:

SELECT COUNT(*)
FROM 
    (SELECT DISTINCT app_color.red
     FROM app_a
     LEFT OUTER JOIN app_color ON app_color.a_id = a.app_a.id
     WHERE app_a.a = a)

with the aggregate we get:

SELECT COUNT(DISTINCT app_color.red) AS n_colors
FROM app_a
LEFT OUTER JOIN app_color ON app_color.a_id = a.app_a.id
WHERE app_a.a = a

So this is done at the database, which is usually faster, and furthermore the amount of data that is transferred from the database to the application is significantly less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM