一、一对多
-
利用ForeignKey 创建表
注关联表中会自动添加字段后面加_id,相当于publish _id,其中单独的publish包含整个Publish对象
class Book(models.Model):
name = models.CharField(max_length=20)
price = models.IntegerField()
pud_data = models.DateField()
publish = models.ForeignKey('Publish')
class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
-
增
- 第一种方法通过真实的字段,也就是在_id添加
def index(request):
from cm import models
obj = models.Book.objects.create(
name = "c#",
price = 200,
pud_data = '2008-08-08',
publish_id= 1
)
print(obj)
return HttpResponse('ok')
- 第二种通过对象添加,具体的操作是先查找出关联对象,把关联对象直接赋值給属性
-
查
- 正向查找通过对象包含查找
def index(request):
from cm import models
obj = models.Book.objects.filter(name="python")
print(obj[0].publish.city)
return HttpResponse('ok')
-
反向查找,通过关联对象查找
- 第一种通过对象反差
def index(request):
from cm import models
obj = models.Publish.objects.filter(name="理工")[0]
obj1 = models.Book.objects.filter(publish=obj).values("name")
print(obj1)
return HttpResponse('ok')
- 第二种通过set反查,通过关联的类后面加_set
def index(request):
from cm import models
obj = models.Publish.objects.filter(name="理工")[0]
obj1 = obj.book_set.all()
print(obj1)
return HttpResponse('ok')
- 第三种直接属性双下滑下接字段,例如publish__name
def index(request):
from cm import models
obj = models.Book.objects.filter(publish__name="理工").values("name")
print(obj)
return HttpResponse('ok')
二、多对多
-
利用ManyToManyField创建表
class Book(models.Model):
name = models.CharField(max_length=20)
price = models.IntegerField()
pud_data = models.DateField()
authors = models.ManyToManyField('Author')
class Author(models.Model):
name = models.CharField(max_length=32)
-
查
利用查询包含ManyToManyField对象,进行查找关联表
def index(request):
from cm import models
obj = models.Book.objects.filter(name="go")
print(obj[0].authors.all().values('name'))
return HttpResponse('ok')
-
增加add,先找到关联对象,在有add添加对象
def index(request):
from cm import models
obj = models.Author.objects.all()
obj1 = models.Book.objects.filter(name="python")
obj1[0].authors.add(*obj)
return HttpResponse('ok')
- 或者直接添加主键
def index(request):
from cm import models
obj = [1,2]
obj1 = models.Book.objects.filter(name="python")
obj1[0].authors.add(*obj)
return HttpResponse('ok')
-
remove删除
def index(request):
from cm import models
obj = [1,]
obj1 = models.Book.objects.filter(name="python")
obj1[0].authors.remove(*obj)
return HttpResponse('ok')