Django framework using process (c)

The development process of learning for each module quickly familiar with Django framework

First, test data

Django ORM module comes, we only need to be familiar with the commonly used ORM operation can be accomplished by the original SQL statement in order to achieve the object-oriented form of CRUD.

When the server has not been started, using the shell command is very easy to test operation of the database environment

Manage.py into the python shell in the same directory, a simple model API exercises

python manage.py shell

Second, the basic object data test

The introduction of the package you want:

from booktest.models import Book,Hero

1, the query all book information:

Book.objects.all ()
method comes django model class objects can be called in response manager directly

2, the new book information:

Book = B ()
b.title = "Shooting Heroes"
b.save ()
when the call save method stores the data into the database

4, modify library information:

= 3.5 of b.price
b.save ()
when calling a save method is equivalent to executing the update method

5, delete Book Information:

b.delete ()
when performing delete the data corresponding to the data deletion difficulties

Third, the operation of the associated object

When there is a correlation objects one to one, one to many, you can use the query associated with many relationships, many here only for example, follow-up courses will be many-to-one relationship.

1. Create an Association Object

Hero = H ()
h.Name = 'Guo Jing'
h.content = 'beating dragon 18 palms'
h.book = B
h.save ()
Book Hero foreign key field of the table, where necessary in accordance with the relevant foreign key constraints assignment

2, multi-many relationship by looking for a party, where the case is to find books by hero

h.book.name
because the relationship is stored in the multi-field, you can find a party through a multi-key field

3, look for multi-many relationship by one party, where to find all cases in which the hero is by the book

b.hero_set.all ()
one object. .all lowercase multi-class name ()

4, if the foreign key is defined using fields related_name

Alternatively it may be used directly as the value hero_set

book = models.ForeignKey (Book, on_delete = models.CASCADE, related_name = 'heros')
query can be used

b.heros.all()

ORM provides a lot of object-oriented statement, to name the most widely used here, the follow-up program will be applied to more ORM statement
Here Insert Picture Description

Published 14 original articles · won praise 4 · Views 9092

Guess you like

Origin blog.csdn.net/zhangzhaoyuxunlei/article/details/104729478