Home  >  Article  >  Backend Development  >  Introduction to common ORM operation examples in Django

Introduction to common ORM operation examples in Django

巴扎黑
巴扎黑Original
2017-09-15 10:50:331615browse

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