search
HomeBackend DevelopmentPython TutorialIntroduction to common ORM operation examples in Django

Introduction to common ORM operation examples in Django

Sep 15, 2017 am 10:50 AM
djangointroduceExample

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:

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

# all(): Query all results

# 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()--------

# 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

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

# order_by(*field): Sort the query results

# reverse(): Reverse sort the query results

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

#

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

# first(): Returns the first record

# last(): Returns the last record

# 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
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
Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

What is a lambda function?What is a lambda function?Apr 28, 2025 pm 04:28 PM

Article discusses lambda functions, their differences from regular functions, and their utility in programming scenarios. Not all languages support them.

What is a break, continue and pass in Python?What is a break, continue and pass in Python?Apr 28, 2025 pm 04:26 PM

Article discusses break, continue, and pass in Python, explaining their roles in controlling loop execution and program flow.

What is a pass in Python?What is a pass in Python?Apr 28, 2025 pm 04:25 PM

The article discusses the 'pass' statement in Python, a null operation used as a placeholder in code structures like functions and classes, allowing for future implementation without syntax errors.

Can we Pass a function as an argument in Python?Can we Pass a function as an argument in Python?Apr 28, 2025 pm 04:23 PM

Article discusses passing functions as arguments in Python, highlighting benefits like modularity and use cases such as sorting and decorators.

What is the difference between / and // in Python?What is the difference between / and // in Python?Apr 28, 2025 pm 04:21 PM

Article discusses / and // operators in Python: / for true division, // for floor division. Main issue is understanding their differences and use cases.Character count: 158

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!