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)
qianchuaner@sina.com