Home Backend Development Python Tutorial Introduction to common ORM operation examples in Django

Introduction to common ORM operation examples in Django

Sep 15, 2017 am 10:50 AM
django introduce Example

The following editor will bring you a detailed explanation of commonly used ORM operations in Django. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

Django process:

1 Create a Django project: django-admin startproject projectname

2 Create an application: : python manage.py startapp appname

3 Create a mapping relationship between url and view function in the controller (urls.py) (one-to-one correspondence)

4 Create a view function , complete the logic code

5 Get the collection object from the database

5 Embed the database variables into the template for rendering (render method)

6 Return the rendered html page to Client

URL: protocol+domain name+port+path

Protocol: http
Domain name: www.cnblogs.com
Port: 80
Path: yuanchenqi/articles/6811632.html
Data: a=1

The regular expression in the URL configuration matches the path part of a url

TEMPALTE (template): HTML code + logic control code

Logic control syntax: {{}} rendering variable filter: {{var|method:parameter}}

{% %} rendering Tag
{% if %}
{% for %}
{% url %}
{% url %}

Custom filter and simpletag:

(1) Create the templatetags module in the app (required)

(2) Create any .py file, such as: my_tags.py

from django import template
register = template.Library()
@register.filter
def filter_multi(v1,v2):
return v1 * v2

(3) Create any .py file, such as: my_tags.py

Import the previously created my_tags.py into the html file using custom simple_tag and filter: {% load my_tags %}

(4) Use simple_tag and filter:

{% load xxx %} #First line
# num=12
{ { num|filter_multi:2 }} #24

Summary:

filter: can only accept one parameter, But you can use if and other statements

simpletag: Can accept multiple parameters, but you cannot use if and other statements

ORM:

Relationship between tables:

One-to-many foreign key field must be in the sub-table (one-to-many-many table) Foreign KEY

Many-to-many in The third table is implemented by adding unique constraints on the basis of two Foreign KEY

one-to-one foreign key fields.

Use mysql method

1Change the setting file db configuration

2Change the driver configuration in the __init__ file

ORM to sql configuration

Configuration of logging in settings

Table.object.filter(): What is obtained is a collection object such as [obj1, obj2]

Table.object.get(): What is obtained is a model object

Add one-to-many records:

#Method 1:

# Book.objects.create(id=1,title="python",publication_date="2017-03-04",price=88.8,publisher_id=1)

#Method 2

p1=Publisher.objects.get(name="Renmin University Press")
Book.objects.create(id=2,title="python",publication_date="2017-05-04",price=98.8, publisher=p1)

Create a many-to-many relationship in the models.py file

authors=models.ManyToManyField("Author") #Many-to-many if the table is in You need to add quotation marks below

Many-to-many addition

ManyToMany has only one way to add:

book.authors.add(*[author1 ,author2])
book.authors.remove(*[author1,author2])

Note: Understand book_obj.publisher

book_obj.authors

Self-built third table

class Book2Author(models.Model):
author=models.ForeignKey("Author")
Book= models.ForeignKey ("Book")
# Then there is another way:
author_obj=models.Author.objects.filter(id=2)[0]
book_obj =models.Book.objects.filter(id =3)[0]

s=models.Book2Author.objects.create(author_id=1,Book_id=2)
s.save()
s=models.Book2Author(author=author_obj ,Book_id=1)
s.save()

.value and .value_list operate the book table book

#value and the result is not an object but an object The result of a field or attribute is also querySet

ret1=Book.objects.values('title')
ret1_list = Book.objects.values_list('title')
print('ret1 is : ',ret1) #The result is: ret1 is :
print(ret1_list) #The result is the list in querySet

The difference between the modification operation update and save:

Update only sets the specified fields and saves all fields, so update is more efficient.

Query:

Expanded content

# Query related API:

# <1>filter(**kwargs): It contains objects that match the given filter conditions

# <2>all(): Query all results

# <3>get(**kwargs): Returns objects that match the given filtering conditions. There is only one returned result. If there are more than one objects or none that match the filtering conditions, an error will be thrown.

#-----------The following methods are all for processing the query results: For example, objects.filter.values()--------

# <4>values(*field): Returns a ValueQuerySet - a special QuerySet. What you get after running is not a series of model instantiated objects, but an iterable dictionary sequence

# <5>exclude(**kwargs): It contains objects that do not match the given filter conditions

# <6>order_by(*field): Sort the query results

# <7>reverse(): Reverse sort the query results

# <8>distinct(): Remove duplicate records from the returned results

# <9> ;values_list(*field): It is very similar to values(). It returns a sequence of tuples, and values ​​returns a sequence of dictionaries

# <10>count(): Returns matches in the database The number of objects in the query (QuerySet).

# <11>first(): Returns the first record

# <12>last(): Returns the last record

# <13> exists(): If the QuerySet contains data, it returns True, otherwise it returns False

The above is the detailed content of Introduction to common ORM operation examples in Django. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

How to use the Django framework to create a project in PyCharm How to use the Django framework to create a project in PyCharm Feb 19, 2024 am 08:56 AM

Tips on how to create projects using the Django framework in PyCharm, requiring specific code examples. Django is a powerful Python Web framework that provides a series of tools and functions for quickly developing Web applications. PyCharm is an integrated development environment (IDE) developed in Python, which provides a series of convenient functions and tools to increase development efficiency. Combining Django and PyCharm makes it faster and more convenient to create projects

Introduction to the eighth color weapon of Neon Abyss Introduction to the eighth color weapon of Neon Abyss Mar 31, 2024 pm 03:51 PM

The eighth color is a weapon in Neon Abyss. Many players want to know about the ballistics of the eighth color of the weapon and how to play with the weapon strength. So let’s take a look at the detailed guide to Neon Abyss’ eighth color weapon trajectory, weapon strength, and weapon gameplay. Neon Abyss Color 8 Detailed Guide Weapon Introduction: The Wizard’s Secret Weapon! Weapon attack speed: Normal Weapon strength: Moderate Weapon gameplay: The attack method of the eighth color is three single-target attacks and then launches a ray. Ballistic display:

See all articles