django ORM

2023-03-16 hit count image

let's see what ORM(Object-Relational Mapping) is and how to create, read, update, delete a data via django ORM(Object-Relational Mapping).

Outline

in this blog post, we’ll see what is ORM(Object-Relational Mapping) and how to use it to create, read, update, delete(CRUD - Create Read Update Delete) a data to the database.

this blog is a series. if you want to check other blog posts of the series, see the links below.

also, this blog series source code is opened on Github. you can see full source code via the link below.

What Is ORM?

ORM(Object-Relational Mapping) means to Map(ping)Object and Relational database. simply, to map the database table and object makes CRUD is possible without SQL query.

we’ve already prepared to use django ORM(Object-Relational Mapping) in the previous blog post(Use Models in django). in the previous blog post, we’ve been mapping the Post Models to the database blog_post table. we’ll use this Models to understand how to CRUD with django ORM(Object-Relational Mapping).

execute the djanog command below to execute Shell that django basically provides.

# source venv/bin/activate
# cd django_exercise
python manage.py shell

import Post Models to execute the code below.

>>> from blog.models import Post

Read Data

execute the code below to Read all Post data.

Post.objects.all()

after executing well, you can see the result like below.

>>> Post.objects.all()
<QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>]>

execute the code below to import User Models and store User data to a variable for later.

>>> from django.contrib.auth.models import User
>>> admin = User.objects.get(username='dev-yakuza')

Create Data

execute the code below to Create a new Post data.

Post.objects.create(author=admin, title='This is a test title from django shell', content='This is a test title from django shell. This is a test title from django shell.')

after it, you can see the result like below.

>>> Post.objects.create(author=admin, title='This is a test title from django shell', content='This is a test title from django shell. This is a test title from django shell.')
<Post: This is a test title from django shell>

Check Data Creation

execute the code below to check the data stored well in Post Models.

>>> Post.objects.all()
<QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>, <Post: This is a test title from django shell>]>

open the new terminal and execute the django command below to start the test server. and then, when you see the administrator page, you can see the data stored well in the screen below.

# source venv/bin/activate
# cd django_exercise
python manage.py runserver
check the data in django administrator page

you can use database tools to check the data stored well.

use database tools to check data stored well

Update Data

execute the code below to Read and Update the data.

post = Post.objects.get(title='This is a test title from django shell')
post.title = 'This is a test title updated from django shell'
post.save()

execute the code below to check the data updated.

Post.objects.get(title__contains='updated')
# or
Post.objects.filter(title__contains='updated')

also, we can use the function we defined before in the Post Models to update.

post = Post.objects.get(title__contains='updated')
# post.published_at
post.publish()
# >>> post.published_at
# datetime.datetime(2019, 5, 21, 13, 1, 58, 970677)

Delete Data

execute the code below to Delete the data we created above.

post = Post.objects.get(title__contains='updated')
post.delete()
# >>> Post.objects.all()
# <QuerySet [<Post: this is a test1 title>, <Post: this is a test2 title>]>

Select(Read) Condition

so far, we saw how to CRUD(Create Read Update Delete) to the database. below is about selection conditions to select(read) a data

  • Selection(Read) Condition
ConditionDescriptionUsage
__containsquery data contains the condition text.Post.objects.filter(title__contains=’test’)
__icontainsquery data contains the condition text without distinction of upper-lower case.Post.objects.filter(title__icontains=’this’)
__ltquery data less than(lt) condition valuePost.objects.filter(published_at__lt=timezone.now())
__ltequery data less than or equal(lte) condition valuePost.objects.filter(published_at__lt=timezone.now())
__gtquery data greater than(gt) condition valuePost.objects.filter(published_at__gt=timezone.now())
__gtequery data greater than or equal(gte) condition valuePost.objects.filter(published_at__gte=timezone.now())
__inquery data by condition value list.Post.objects.filter(id__in=[1, 2, 3])
__yearquery data by condition yearPost.objects.filter(created_at__year=’2019’)
__yearquery data by condition monthPost.objects.filter(created_at__month=’5’)
__dayquery data by condition dayPost.objects.filter(created_at__day=’21’)
__isnullquery data by null conditionPost.objects.filter(published_at__isnull=True)
__startswithquery data starting with condition text.Post.objects.filter(title__startswith=’This’)
__istartswithquery data starting with condition text without deistinction of upper-lower casePost.objects.filter(title__istartswith=’this’)
__endswithquery data ending with condition text.Post.objects.filter(title__endswith=’title’)
__iendswithquery data ending condition text without distinction of upper-lower casePost.objects.filter(title__iendswith=’title’)
__rangequery data by condition range(= SQL between feature)Post.objects.filter(id__range=(1, 10))
  • Exclusion Condition: we can select the data with exclusion condition.
Post.objects.all().exclude(title__contains='This')
  • Multiple Condition: we can select the data with multiple condition like below.
Post.objects.filter(title__contains='this', title__endswith='title')
Post.objects.filter(title__contains='this').filter(title__endswith='title')

from django.db.models import Q
Post.objects.filter(Q(title__contains='this') | Q(title__endswith='title'))
Post.objects.filter(Q(title__contains='this') & Q(title__endswith='title'))
  • 조회 범위: 아래와 같이 가져올 데이터의 범위(limit)을 지정할 수 있다.
Post.objects.all().exclude(title__contains='This')[:1]

Ordering(Sorting)

we can order(sort) the data ascending or descending.

  • Ascending: Post.objects.order_by(‘created_at’)
  • Descending: Post.objects.order_by(‘-created_at’)

Exit Shell

so far, we exercised django ORM(Object-Relational Mapping) with django Shell. execute the code below to exit django Shell.

exit()

Completed

we saw what is ORM(Object-Relational Mapping) and how to use it on django. ORM(Object-Relational Mapping) is the concept used in many frameworks, so I think remembering it is good for us. anyway, now we can create, read update and delete(CRUD - Create Read Update Delete) the data with django Models!

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts