Using Django QuerySet


Django Querysey

Running shell

python3 manage.py shell

It will oppen command line. Before using QuerSet, you need to import your model here

from .models import Task

QuerySet

from django.shortcuts import render, get_object_or_404,
from .models import Task

task_list = Task.objects.all()

task = get_object_or_404(Task, title="some title")

task_list = Task.objects.filter(date_created__year=2022)

Simple where clause

Task.objects.filter(title="First Task")
Task.objects.exclude(title="John")


# These two are same
Task.objects.filter(title="First Task")
Task.objects.all().filter(title="First Task")

AND Clause

Dog.objects.create(name='Max', data=None)

Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
#This is same as 
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

OR Clause

User.objects.filter(first_name="John") | User.objects.filter(first_name="Jane")

Select Query with where clause

Entry.objects.get(headline__contains='Lennon')
Task.objects.filter(title__startswith="First")
Task.objects.all().filter(title__endswith="Task")

Entry.objects.filter(pub_date__lt='2006-01-01')
Entry.objects.filter(pub_date__lte='2006-01-01')
Entry.objects.filter(mod_date__gt='2006-01-01')
Entry.objects.filter(mod_date__gte='2006-01-01')

Limiting the outset

Entry.objects.all()[:5]

post by Pravin

#django

Comments