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 a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

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

Adv 120x600

Looking for advertising?

Consider These Things If You Appreciate What stackorigin Does: Stackorigin is a community where you can ask questions and find answers, for free to everyone. We would appreciate it if you bought us a coffee if you liked what we were doing.

Buy me a Coffe

Adv 120x600

  • Random
  • Answers
    • On: March 20, 2023
    • Answers: 0

    HTTP 503 (Service unavailable) error when using an Application Load ...

    • On: August 7, 2022
    • Answers: 0

    How to purchase Medrol without prescription, Medrol (pak) 4mg tablets

    • On: August 6, 2022
    • Answers: 0

    Kaufen Sie Pepcid, Pepcid or zantac for nausea

    • On: August 4, 2022
    • Answers: 0

    Avodart Singapore, Avodart lloyds pharmacy

    • On: August 3, 2022
    • Answers: 0

    where can i buy Feldene, Feldene and tylenol

  • strapcart_online
    strapcart_online added an answer Sildenafil citrate is a common ingredient in Cenforce 150mg tablets. This drug… March 21, 2023 at 11:42 am
  • strapcart_online
    strapcart_online added an answer Vilitra 20mg tablets are used to overcome the problem of… March 18, 2023 at 6:13 am
  • ashok
    ashok added an answer Not every girl, there are some girls out there who… March 16, 2023 at 4:15 am
  • strapcart_online
    strapcart_online added an answer Tadarise 40 Tablet is used to permanently remove the problem… March 4, 2023 at 5:48 am
  • strapcart_online
    strapcart_online added an answer Men use Cenforce D tablets for the treatment of sexual… March 1, 2023 at 5:59 am

Adv 120x600

Trending Categories

Health
2042Questions
, 4Followers
Programming
1236Questions
, 0Followers
Technology
216Questions
, 3Followers
General Knowledge
131Questions
, 0Followers
Business & Finance
84Questions
, 4Followers

Adv 120×600

Stats

  • Questions 4k
  • Answers 1k
  • Best Answers 105
  • Users 100

Users

niyadas823

niyadas823

  • 0 Questions
  • 0 Answers
nirala3

nirala3

  • 2 Questions
  • 0 Answers
Perrywalton

Perrywalton

  • 1 Question
  • 0 Answers
veeraa

veeraa

  • 0 Questions
  • 0 Answers
Stewesmitz

Stewesmitz

  • 0 Questions
  • 0 Answers

Adv 120×600

Explore

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

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.