Introduction to common ORM operation examples in Django
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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 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

In Hua Yishan Heart Moon, Lu Shu is an SSR celebrity. He is positioned as a single-target backline player and has a very impressive critical hit rate. Many players don’t know much about Lu Shu. Here’s what I’ve brought you. Come and take a look at the introduction to the skills and attributes of Hua Yishan Heart of the Moon Lu Shu. Celebrity Attributes Celebrity Skills 1. Lu Ming Shuzhong Skill Description: Lu Shu was born in Qiongqihui in Shuzhong. He has practiced martial arts since he was a child and has outstanding martial arts skills. Causes basic attack damage equal to 100% of the enemy's back row attack power, and reduces the target's rage by 10 points. Skill attributes: Level 2: Basic attack damage increased to 105%. Level 2: Basic attack damage is increased to 110%, and the target's rage is reduced by 15 points. Level 2: Basic attack damage increased to 115%. Level 2: Basic attack damage is increased to 120%, and the target's rage is reduced by 20 points. Level 2: Basic attack

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.

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

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold
