Django filter

Posted under » Django on 22 July 2022

Continued from Django API.

Django filter is different from SQL. Instead of 'node_id=22 AND difficulty_of_question=1 AND bundle=2' and 'LIMIT 2' you

Question.objects.filter(node_id=22,difficulty_of_question=1,bundle=2) [:2]

If you want to count them,

kira = Question.objects.filter(node_id=22,difficulty_of_question=1,bundle=2).count() 

There is no OR. The equivalent is like PHP operators.

rfa = Question.objects.filter(id=10) | Question.objects.filter(id=20)

Using Q

from django.db.models import Q     

rfa = Question.objects.filter(
... Q(id=10)|Q(id=20)

If you want to exclude id=3

from django.db.models import Q

Entry.objects.filter(~Q(id=3))

If you want to fetch its corresponding SQL code by executing the following command.

str(rfa.query)

If you want to get the first letters, eg. choosen starts with “n”

initial = Note.objects.filter(choosen_startswith="n")

If you want to use the contains filter or SQL LIKE '%nafi%'

initial = Note.objects.filter(choosen_contains="nafi")

If you have an array, you can use the IN operator.

If you want to exlude stuff instead

initial = Note.objects.exclude(choosen_startswith="n")

Or most common use of exclude is NULL

maslery = Progress.objects.filter(user_id=1).exclude(mastery__isnull=True).last()

Greater than = gt and greater than OR equal to >=

initial = students.objects.filter(age_gt=18)
initial = students.objects.filter(age_gte=18)

Lesser than = lt

initial = students.objects.filter(age_lt=18)

QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated.

initial = Note.objects.filter(choosen="n2")
initial = Note.objects.order_by('node_id')

Only the sort order is made but the filter is not. You should do like below.

Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

In SQL, we use the DISTINCT keyword in the SELECT statement to select unique records. We generally use the SELECT DISTINCT statement to remove all the duplicate records.

queryset = students.objects.values('course').distinct()

See also Difference between PHP and Python.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data