django query to filter and distinct

24,324

Solution 1

Try this:

from django.db.models import Q
example.objects.exclude(
      Q(values__isnull=True)|Q(values='')
    ).values_list('values', flat=True).distinct()

Solution 2

As other answers mentioned, if you have a null/empty string confusion. You might exclude both using complex lookup parameters like:

from django.db.models import Q
example.objects.exclude(Q(values__isnull=True)|Q(values='')).values_list('values',flat = True).distinct()

Complex Lookups are here...

Solution 3

You can try filtering out the null values first and then chain your filter, as below

example.objects.exclude(values=None).values_list('values',flat = True).distinct()
Share:
24,324
sankar
Author by

sankar

Updated on July 09, 2022

Comments

  • sankar
    sankar 3 months

    I have a table as follows:

    table_name : example

    values
    1
    1
    2
    
    2
    3
    
    3
    

    the value list contains the values as above. When i write a distinct query on the able table, i get 1 2 3 and a empty '' value.

    I want to get rid of the null value as it is posing some problems in my program. the query for that which i have written is:

    example.objects.values_list('values',flat = True).distinct()
    

    Is there a a way to filter out that empty value