1.创建表模型
'''
(一)多表查询
一对一:models.OneToOneField(to_field='id',to='Authordatil')
一对多:(外键设置唯一性)
models.ForeignKey(to='Publish',to_field='id')
多对多:自动生成第三张表
models.ManyToManyField(to='Author')
(二)创建表模型
作者与详情 ( 一对一 )
书与作者( 多对多 )
出版社与书(一对多 )
出版社:id name add email
书: id name price publish
作者: id name sex authordatil
详情: id photo address
'''
from django.db import models
class Publish(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
address = models.CharField(max_length=64)
email = models.EmailField()
def __str__(self):
return '%s,%s,%s'%(self.name,self.address,self.email)
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5,decimal_places=2)
publish = models.ForeignKey(to='Publish',to_field='id')
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.name
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
choices = ( (0,"女"),(1,"男") )
sex = SmallIntegerField( choices=choices, default=0 )
authordatil = models.OneToOneField(to_field='id',to='Authordatil')
def __str__(self):
return self.name
class Authordatil(models.Model):
id = models.AutoField(primary_key=True)
photo = models.CharField(max_length=32)
address = models.CharField(max_length=32)
- id 字段是自动添加的
- 对于外键字段,Django 会在字段名上添加"_id" 来创建数据库中的列名
- 外键字段 ForeignKey 有一个 null=True 的设置(它允许外键接受空值 NULL),你可以赋给它空值 None 。
2.添加/删除/修改表记录
li = []
for i in range(100):
li.append(models.Book(name='图书%s'%i,price=10+i))
models.Book.objects.bulk_create(li)
Authordatil = Authordatil.objects.create(photo=121212121,address='东莞')
auther = Auther.objects.filter(name = '西游记').update( publish_id=1 )
auther = Auther.objects.filter("name" = "西游记").first()
auther.name = "东游记"
auther.save()
auther =Auther.objects.filter(name = '西游记').delete()
book = Book.objects.create(name='三国',price=56,publish_id=1)
publish = Publish.objects.get(id=1)
book = Book.objects.create(name='西游记',price=26,publish=publish)
book = Book.objects.filter(name = '西游记').update( publish_id=1 )
publish = Publish.objects.get(id=3)
book = Book.objects.filter(name = '西游记').update(publish=publish)
book = Book.objects.filter(name='西游记',price=22).delete()
'''
增:add ( obj1,obj2... ) 可以传对象,可以传id,可以传多个
删:remove( obj1,obj2... ) 可以传对象,可以传id,可以传多个
改:先清空,配置
清空: clear() 清空所有
配置:set() 里面传列表,里面可以是对象或者是id *注意先清空,在配置
'''
zxx = Author.objects.filter(name='zxx').first()
yxx = Author.objects.filter(name='yxx').first()
book = Book.objects.filter(name='西游记').first()
book.authors