Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django query to filter and distinct

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

like image 366
sankar Avatar asked Sep 04 '12 11:09

sankar


People also ask

What is distinct () in Django QuerySet?

distinct() Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results. By default, a QuerySet will not eliminate duplicate rows.

How do I get unique records in Django?

We can use a distinct() query method at the end or in between queryset and with other regular Django query methods like all(), values(), etc…

What is difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


1 Answers

Try this:

from django.db.models import Q
example.objects.exclude(
      Q(values__isnull=True)|Q(values='')
    ).values_list('values', flat=True).distinct()
like image 58
Andre Bossard Avatar answered Oct 12 '22 06:10

Andre Bossard