Django Models Part 3 (Model Manager, QuerySet, Lookups)

Search for a command to run...

No comments yet. Be the first to comment.
This series will cover the core concepts on web application development using Django, from basic installation to user authentications and some core concepts. Status: 9/14 published ✅
Model Field Validation To validate a model field on application level we can create up a validator which is a callable that take the value to be validated and raises error (ValidationError to be precise) if the value doesn't meet the criteria or it i...
Nothing serious, just experimenting on Django Framework

Working with simple media uploads and serving these media files

Using static files like JavaScript, CSS, images with Django

Class() based views in Django

function() based views in Django

Manager is the interface through which we perform ORMs in Django modelsManager with a name of objects. This is the reason we are able to use objects and query to our Models eg: Model.objects.all()Example to change rename default objects in our model
from django.db import models
class Info(models.Model):
name = models.CharField(max_length=100)
data = models.Manager()
# Info.objects.all() will not work but Info.data.all() will work
(loop, slice with increments,...), it doesn't hit your database. So, we call it by saying QuerSet is Lazyfrom django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
filter()
users whose age=10, we can do User.objects.filter(age=10);qs = User.objects.filter(age=10)
for u in qs:
print(u.name, u.age)
AND clause when crafting an SQL queryUser.objects.filter(age=10, name="John") will return list of users whose age is 10 AND whose name is JohnOR you can use Q objects. e.g. This example will return list of users whose name is John OR Harry from django.db.models import Q
qs = User.objects.filter(Q(name='John') | Q(name='Harry'))
exclude()
filter() multiple arguments/parameters are joined by AND clauseUser.objects.exclude(age=20) will return list of users whose age is not 20order_by()
If you have set default ordering for your models, you don't even have to use this method to order your QuerySet, because the results returned by QuerySet are ordered automatically by the ordering tuple given by the ordering option in models Meta
class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Meta:
ordering = ['-age'] # - negative sign for descending order and
# no sign for asc order
User.objects.filter(age=10) on this model will return the list of users whose age is 10 in descending order of ageUser.objects.filter(age=10).order_by('age') on this model will return the list of users whose age is 10 in ascending order of ageUser.objects.order_by('-name') will return list of users in descending ordernone()
none() will create a QuerySet that will never return any objectsQuerySet but no datanone() will not hit databaseUser.objects.none()all()
User.objects.all() will return list of every users/objectsUser.objects.get(id=1) will return the row/object whose id is 1User.objects.create(name="Peter",age=25) will create a new object/record in database and return that objectUser.objects.filter(id=10).first() will return the first row/object whose id is 10User.objects.filter(id=10).last() will return the last row/object whose id is 10User.objects.filter(id=10).delete() will delete objects/rows whose id is 10. This works like a bulk deletedelete() on model single objects like the objects obtained from get() first() last() methods. This works like a single object deleteUser.objects.filter(id=10).count() will return total number of users/objects whose id is 10WHERE clausefield_[LookupType]=value [note the double underscores]exact (also a default lookup)
User.objects.filter(name__exact="Peter") would generate SQL: select .... where name="Peter" and returns the objects/rows whose name is PeterIf we do not provide a lookup like in the above
QuerySetmethod examples, Django automatically usesexactlookup. This is the reason our ORMs were working even when we didn't pass any lookups
User.objects.filter(name__exact="Peter") and User.objects.filter(name="Peter") QuerySet is practically the sameiexact
User.objects.filter(name__iexact="peter") would return QuerySet of the list of users whose name is peter(case insensitive) i.e: peter, Peter, PeTeR, peteR e.t.ccontains
User.objects.filter(name__contains="a") would generate SQL: select ..... where name like '%a%' and would return QuerySet of list of users whose name contains/includes aicontains
contains but case-insensitivegt
User.objects.filter(age_gt=10) would return QuerySet of list of users whose age is greater than 10 i.e 11,12,13,.......gte
User.objects.filter(age_gte=10) would return QuerySet of list of users whose age is greater than or equals to 10 i.e 10,11,12,13,.......lt
User.objects.filter(age_lt=10) would return QuerySet of list of users whose age is less than 10 i.e 9,8,7,......lte
User.objects.filter(age_lte=10) would return QuerySet of list of users whose age is less than or equals to 10 i.e 10,9,8,7,.....There are other plenty of inbuilts lookups. To name some of them;
instartswithistartswithrange