Python Learning---Django's ORM syntax [Object Relational mapping]180124

Source: Internet
Author: User

ORM syntax [Object Relational Mapping]

ORM: The object-oriented way to manipulate the database creation table and adding and removing changes and other operations.

Pros:The 1 ORM makes our universal database interaction easy and completely free of the damned SQL statements. Rapid development.

2 can avoid some novice program ape writing SQL statements brought about by performance problems.

Cons:1 performance sacrifices, but now the various ORM frameworks are experimenting with various methods, such as caching, delaying the loading of the login to alleviate the problem.

2 for individual complex queries, ORM is still inadequate, and in order to solve this problem, ORM generally supports writing raw SQL.

3 querying the SQL statement for the corresponding operation via the Queryset query property

Author_obj=models. Author.objects.filter (id=2)

Print (Author_obj.query)

CREATE TABLE [Class class CREATE TABLE]:

One to one: Onetoone

One-to-many: foreignkey[foreign key in more that class/table]

Many-to-many: Manytomany

ORM Operation

CREATE TABLE [class class CREATE TABLE]:
One to one: Onetoone
One-to-many: foreignkey[foreign key in more that class/table]
Many-to-many: Manytomany
action table [Row object]:
Increase:
Create
1 Increase in single table
Models. Book.objects.create (name= ' FTL ')
Single table added 2 "Recommended"
dict={' name ': ' FTL '}
Models. Book.objects.create (**dict) # receive the dictionary passed over
1 "Foreign key publish" added to a one-to-many table
Models. Book.objects.create (name= ' FTL ', publish_id=2) # Add ID directly
A one-to-many table added 2 "Foreign key publish, recommended to add according to the object"
Publisher=models. Publish.objects.get (id=2)
# Add a single object, non-set "otherwise it becomes many-to-many"
Models. Book.objects.create (name= ' FTL ', publish=publisher)
Many-to-many "recommended object additions"
Publisher=models. Publish.objects.get (id=2)
Publisher1=models. Publish.objects.get (id=3)
Book=models. Book.objects.get (id=2)
Book.add (PUBLISH,PUBLISH1)
Or direction add: Author.book_setadd (*books) [Books is list]
Save
Single table Create 1, book = Book (name= ' FTL ')
Book.save ();
Single table Create 2, book = Book ()
Obj.name= ' FTL '
Ojb.save ()
Multi-table Creation ditto create ()
Delete:Delete, remove, clear
Change:Update, save
Check:Filter, get

To Create a table model:

/blog/models.py

#--------------------------------ORM Learning------------------------from django.db import Modelsclass Publish (models. Model): id = models. Autofield (primary_key=true) name = models. Charfield (' name ', max_length=64) city = models. Charfield (' City ', max_length=64) province = models. Charfield (' Province ', max_length=30, default= ' BJ ') country = models. Charfield (' Country ', max_length=33, default= ' china ') website = models. Charfield (' url ', max_length=30, default= "WWW") class Meta:verbose_name= ' publisher ' verbose_name_plural = Verbos E_name # plural complex def __str__ (self): return Self.nameclass Author (models. Model): name = models. Charfield (' name ', max_length=30) def __str__ (self): return Self.nameclass Authordetail (models. Model): Sex = models. Booleanfield (max_length=1, choices= (0, ' Male '), (1, ' female '))) e-mail = models. Emailfield (' mailbox ', max_length=12) birthday = models. Datefield () Author = models. Onetoonefield (author,on_delete=models. CASCADE,) class book (Models. MoDel): title = models. Charfield (max_length=64, verbose_name= "title") Price = models. Decimalfield (max_digits=5, decimal_places=2, default=10) Page_num = models. Integerfield (null=true,editable=false) # Djangog Default Modifiable # Note is a quoted class, if not added, you need to put the class in front of the class [otherwise the PY interpreter cannot find] Author = models. Manytomanyfield (' Author ', default= ' FTL ') # 1 The book has multiple authors # Author = models.    Manytomanyfield (Author, default= ' FTL ') # Author class must be #外键属性 before book, Django will default to publish when creating the form publish_id[foreign key on more than one side of the creation] Publish = models. ForeignKey (' Publish ', on_delete=models. CASCADE, default=1,) Publish_date = models. Datefield (default= ' 2020-20-20 ') def __str__ (self): return Self.title

To execute a command, create a form:

Python manage.py makemigrations  # will generate a Python file under the Migrations folder under the blog                                       # F:\Django\mysite2\blog\migrations\ Auto_20180125_0737.pypytyon manage.py Migrate         

Build Table Success:

Analysis Code:
<1> Each data model is a subclass of Django.db.models.Model, and its parent class model contains all the necessary methods for interacting with the database. and provides a nice introduction to the syntax for defining database fields.
<2> each model is equivalent to a single database table (a many-to-many relationship exception that generates a relational table), and each property is also a field in the table. The property name is the field name, and its type (for example, Charfield) corresponds to the field type of the database (for example, varchar). You can be aware of the other types that correspond to what fields are in the database.
Three relationships between <3> models: one-to-one, one-to-many, many-to-many.
One: The essence is in the main foreign key (author_id is foreign key) on the basis of the foreign key to add a unique=true attribute;
One-to-many: is the primary foreign key relationship; (foreign key)
Many-to-many: (Manytomanyfield) automatically creates a third table (and of course we can create a third table ourselves: two foreign key)

Problem solving

Encountered issue 1:

Problem: Table field has no default value error, failed to build

Problem Solving: Add property Default value, Py3 new add

Encountered issue 2:

Symptom: FOREIGN key not set cascade Delete, Build table failed

Problem solving: Add cascade Delete, On_delete=models. CASCADE,

Python Learning---Django's ORM syntax [Object Relational mapping]180124

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.