The path to learning in Python -2018/6/26 1.ORM Single-table operation delete and modify records
>>> ret = Book.objects.filter(title="go").delete()(1, {‘app01.Book‘: 1})>>> Book.objects.filter(price=115).update(price=120)
Multiple table operations Create a model
One
models.OneToOneField(to="表名", on_delete=models.CASCADE)
One-to-many
models.ForeignKey(to="表名", to_field="字段名", on_delete=models.CASCADE)
Many-to-many
models.ManyToManyField(to="表名")
models.py
fromDjango.dbImportModelsclassAuthor (models. Model): Nid=Models. Autofield (Primary_key=True) name=Models. Charfield (max_length= +) Age=Models. Integerfield ()# Establish a one-to-one relationship with AuthordetailAuthor_detail=Models. Onetoonefield (To="Authordetail", On_delete=Models. CASCADE)classAuthordetail (models. Model): Aid=Models. Autofield (Primary_key=True) Birthday=Models. Datefield () Telephone=Models. Bigintegerfield () addr=Models. Charfield (max_length= -)classPublish (models. Model): PID=Models. Autofield (Primary_key=True) name=Models. Charfield (max_length= +) City=Models. Charfield (max_length= +) Email=Models. Emailfield ()classBook (Models. Model): Bid=Models. Autofield (Primary_key=True) title=Models. Charfield (max_length= +) publishdate=Models. Datefield () Price=Models. Decimalfield (max_digits=5, decimal_places=2)# Establish a one-to-many relationship with publish, and foreign key fields are built on more than one sidePublish=Models. ForeignKey (To="Publish", To_field="pid", On_delete=Models. CASCADE)"""publish_id INT,FOREIGN KEY (publish_id) REFERENCES publish (PID) """ # Establish Many-to-many relationships with authorAuthors=Models. Manytomanyfield (To="Author")"""CREATE TABLE Book_author (ID INT PRIMARY KEY auto_increment,book_id INT,author_id INT,FOREIGN KEY (book_id) REFERENCES book (BID),FOREIGN KEY (author_id) REFERENCES author (nid), ) """
Operation Result:
Attention:
- On_delete = models. Cascade use a pair and a couple of
- The foreign key field will automatically add _id, such as Publish = models. ForeignKey () generates publish_id after execution
- Need to configure APP01 in settings.py
Add a record
One-to-many
Book.objects.create(title="坏蛋是怎样炼成的", publishDate="2017-01-02", price=125, publish_id=1)
Operation Result:
>>> book = Book.objects.get (Bid= 1 ) >>> print (book.bid) 1 >> print (Book.title) How the villain is refined >>> print (book.publishdate) 2017-01-02 >>> print (Book.price) 125.00 >>> print (Book.publish) Publish object (1 ) >>> print (book.publish.name) China City Press >>> print (book.publish.email ) [email protected]
Python Learning Path -2018/6/26