What is a QuerySet?
QuerySet is, in essence, a list of objects of a given Model. QuerySets allow you to read the data from the database, filter it and order it.
What is an ORM?
ORM is an acronym for the object-relational mapper. Django ORM provides an elegant and powerful way to interact with the database. The ORM’s main goal is to transmit data between a relational database and application model.
Example:
from django.db import models
class Student(models.Model):
surname = models.CharField(max_length=200)
firstname = models.CharField(max_length=200)
other_name = models.TextField(blank=True)
gender = models.TextField(default='male')
date = models.DateField(auto_now=True)
Note: auto_now – updates the value of field to current time and date every time the Model. save() is called. auto_now_add – updates the value with the time and date of creation of record
Let’s start by creating an Student object:
from app.models import Student
a = Student(surname ='jerry', firstname ='tom', other_name ='tj', gender="male")
a.save()
- To save the object to the database call the save() method.
- save() method comes from models.Model class.
Let’s delete the object from the database:
if you want to delete one instance then write the code
entry= Account.objects.get(id=5)
entry.delete()
if you want to delete all instance then write the code
entries= Account.objects.all()
entries.delete()
Defining str() method on model
str() is a special method which tells Python how to display an object in human readable form
class Student(models.Model):
surname = models.CharField(max_length=200)
firstname = models.CharField(max_length=200)
other_name = models.TextField(blank=True)
gender = models.TextField(default='male')
date = models.DateField(auto_now=True)
def __str__(self):
return self.firstname + " : " + self.other_name
we run makemigrations command only in the following two cases:
- When we add/modify fields in the model.
- When we adding/modify Meta classes.
create() method:
create() method allows us to create and commit object to the database. instead of separately calling the save() method.
Student.objects.create(surname="jan", firstname="tom", other_name="",gender="male", date="")
bulk_create() method:
bulk_create() method create and commit multiple objects at a time.
Student.objects.bulk_create([
Student(surname="jan", firstname="tom", other_name="",gender="male", date=""),
Student(surname="jan1", firstname="tom1", other_name="",gender="female", date="")
])
all() method:
all() method fetches all the records from specified table.
Student.objects.all()
count() method:
count() method returns the total number of records in a database table.
Student.objects.all().count()
Student.objects.filter(firstname="john").count()
Student.objects.count()
filter() method:
filter() method returns a subset of data. If we had two records where gender is ‘male’ then filter() would have returned a QuerySet object containing two Author objects.
Student.objects.filter(gender='male')
Django Field Lookups
contains lookup:
- __contains lookup is case-sensitive
- __icontains lookup is case-insensitive
Student.objects.filter(firstname__contains="te")
startswith lookup:
- __startswith lookup finds whose name field start with “j”
- __istartswith lookup is case-insensitive
Student.objects.filter(firstname__startswith="j")
endswith lookup:
- __endswith lookup finds whose name field start with “j”
- __iendswith lookup is case-insensitive
Student.objects.filter(firstname__endswith="ru")
gt and lt lookup:
Student.objects.filter(id__gt=3)
Student.objects.filter(id__lt=3)
# greater than or equal to
Student.objects.filter(id__gte=3)
Student.objects.filter(id__lte=3)
get() method:
get() method returns only single object. If it finds multiple objects it raises a MultipleObjectsReturned exception. If it doesn’t find any object it raises DoesNotExist exception.
Student.objects.get(id=1000)
Ordering Results:
Student.objects.order_by("id") #ASC order
Student.objects.order_by("-id") #DESC order
Selecting the fields:
values_list() method returns a QuerySet where each element is a tuple.
Student.objects.values_list("id", "firstname")
Output:
QuerySet [(1, 'mickle'), (2, 'tom')]
values(): it returns a QuerySet where each element is a dictionary.
Student.objects.filter(id__gt=3).values("id", "name")
Output:
QuerySet [{'id': '4', 'firstname': 'mickle'}, {'id': 5, 'firstname': 'john'}]
Slicing Results
Student.objects.order_by('-id')[1] # returns the 2nd record after sorting the results
Updating Objects
First way:
a = Author.objects.get(id=2)
print(a.firstname) => "john"
a.firstname = "tom"
a.save()
second way:
Student.objects.filter(id=2).update(email='tom@gmail.com')
Deleting records
delete() method is used to delete one or more records.
a = Student.objects.get(pk=2)
a.delete() #to delete specified record
b = Student.objects.all()
b.delete() #to delete multiple records