Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here
Sign InSign Up

Stackorigin – The Community of Question and Answers

Stackorigin – The Community of Question and Answers Logo Stackorigin – The Community of Question and Answers Logo
Search
Ask A Question

Mobile menu

Close
Ask a Question
Home/Django ORM Tutorial

Django ORM Tutorial

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

Share
  • Facebook

Sidebar

Ask A Question

Stats

  • Questions 1k
  • Answers 1k
  • Best Answers 80
  • Users 81

Adv 250x250

Adv 234x60

  • Recent
  • Answers
  • ashok

    How do I get the current time?

    • 2 Answers
  • ashok

    How to Install and Use Git on Windows

    • 1 Answer
  • ashok

    How to Check Git Version

    • 2 Answers
  • arjun

    Which institute is best for a data science course in ...

    • 1 Answer
  • ashok

    git stash and git pull

    • 1 Answer
  • pratap
    pratap added an answer How do I get the current time in Python: The time module… June 29, 2022 at 9:08 am
  • pratap
    pratap added an answer How do I get the current time in Python: Use datetime:… June 29, 2022 at 9:04 am
  • hari
    hari added an answer How to Install and Use Git on Windows Git is… June 29, 2022 at 8:24 am
  • sam
    sam added an answer How to Check Git Version: $ git --version git version… June 29, 2022 at 8:13 am
  • sam
    sam added an answer How to Check Git Version: In a command prompt: $… June 29, 2022 at 8:13 am

New Members

Sakshigupta1998

Sakshigupta1998

  • 0 Questions
  • 0 Answers
legal heir certificate online apply

legal heir certificate online apply

  • 0 Questions
  • 0 Answers
Mutual divorce process india

Mutual divorce process india

  • 0 Questions
  • 0 Answers
propertyregistration

propertyregistration

  • 0 Questions
  • 0 Answers
Best Gynecologist Hospital in Delhi

Best Gynecologist Hospital in Delhi

  • 0 Questions
  • 0 Answers

Adv 234x60

Trending Categories

Programming
825Questions
, 0Followers
Technology
209Questions
, 3Followers
General Knowledge
127Questions
, 0Followers
Business & Finance
81Questions
, 4Followers
Employment
73Questions
, 3Followers

Trending Tags

django (95) git (57) google (29) india (35) mysql (22) oil (54) pandas (23) python (241) usa (25) youtube (24)

Recent posts

    • On: June 29, 2022

    Bitbucket Cloud recently stopped supporting account passwords for Git authentication

    • On: June 21, 2022

    Best Telegram Movie Channels

    • On: June 17, 2022

    How to Open ICICI Bank Savings Account

    • On: June 15, 2022

    How to Download Your Own Twitch Videos

    • On: June 14, 2022

    How To Permanently Delete Your PSN Account

Explore Our Blog

Adv 234x60

Subscribe

Explore

  • Recent Questions
  • Most Answered
  • Answers
  • No Answers
  • Most Visited
  • Most Voted
  • Random

Footer

Stackorigin - The Community of Question and Answers

Stackorigin

Stackorigin is the world’s largest Q&A networking site, Stackorigin community brings you the collaboration of all the various Questions and the related Answers given by the community.

About

  • About Us
  • Contact Us
  • FAQ
  • Submit Guest Post Article on Technology, Education, Health, Apps, Gadgets, IoT, AI, Business, Digital Marketing and More

Info

  • Privacy Policy
  • Terms and Conditions
  • Community Guidelines
  • Tags

Products

  • Tutorials
  • Advertising
  • Categories
  • Corona
  • StackHow

Follow

© 2022 Stackorigin. All Rights Reserved.