1. 程式人生 > >Python學習之路—2018/6/26

Python學習之路—2018/6/26

添加記錄 decimal sin 單表 IT S3 src 壞蛋 char

Python學習之路—2018/6/26

1.ORM

單表操作

刪除與修改記錄

>>> ret = Book.objects.filter(title="go").delete()
(1, {‘app01.Book‘: 1})
>>> Book.objects.filter(price=115).update(price=120)

技術分享圖片

技術分享圖片

多表操作

創建模型

一對一

models.OneToOneField(to="表名", on_delete=models.CASCADE)

一對多

models.ForeignKey(to="表名", to_field="字段名", on_delete=models.CASCADE)

多對多

models.ManyToManyField(to="表名")

models.py

from django.db import models


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # 與AuthorDetail建立一對一關系
    author_detail = models.OneToOneField(to="AuthorDetail"
, on_delete=models.CASCADE) class AuthorDetail(models.Model): aid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.BigIntegerField() addr = models.CharField(max_length=64) class Publish(models.Model): pid = models.AutoField(primary_key=True
) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() class Book(models.Model): bid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) publishDate = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2) # 與Publish建立一對多關系,外鍵字段建立在多的一方 publish = models.ForeignKey(to="Publish", to_field="pid", on_delete=models.CASCADE) """ publish_id INT, FOREIGN KEY(publish_id) REFERENCES publish(pid) """ # 與Author建立多對多關系 authors = 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), ) """

運行結果:

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

註意:

  • on_delete = models.CASCADE在使用一對以及一對多時需要用到
  • 外鍵字段會自動添加_id,比如publish = models.ForeignKey()執行後生成publish_id
  • 需要在settings.py中配置app01

添加記錄

一對多

Book.objects.create(title="壞蛋是怎樣煉成的", publishDate="2017-01-02", price=125, publish_id=1)

運行結果:

技術分享圖片

>>> book = Book.objects.get(bid=1)
>>> print(book.bid)
1
>>>print(book.title)
壞蛋是怎樣煉成的
>>> print(book.publishDate)
2017-01-02
>>> print(book.price)
125.00
>>> print(book.publish)
Publish object (1)
>>> print(book.publish.name)
中國城市出版社
>>> print(book.publish.email)
[email protected]

Python學習之路—2018/6/26