3.17 Django数据库多对多
在Django中,多对多关系通常通过一个自动创建的中间模型来实现。这个中间模型包含了两个外键,分别指向多对多关系的两端。
示例:
python
#创建models
class Auther(models.Model):
name=models.CharField(verbose_name='作者',max_length=32)
class Book(models.Model):
title=models.CharField(verbose_name='书名',max_length=128)
#auther为MToM类型,并关联到Auther
auther=models.ManyToManyField(verbose_name='作者',to=Auther,related_name='books')
#逻辑:一个作者可以有多本书,一本书可以有多个作者
执行" python manage.py makemigrations"和"python manage.py migrate "后数据库中会生成三张表
auther:作者表
book:书本表
book_auther:关联表
python
#添加数据
models.Auther.objects.create(name='sally')
models.Auther.objects.create(name='muyi')
models.Auther.objects.create(name='ying')
#创建三个对象
auther_obj1=models.Auther.objects.filter(name='sally').first()
auther_obj2=models.Auther.objects.filter(name='muyi').first()
auther_obj3=models.Auther.objects.filter(name='ying').first()
#插入书本数据
book_obj1=models.Book.objects.create(title='sally_book1')
book_obj2=models.Book.objects.create(title='sally_book2')
#将书本1和书本2关联到作者auther_obj1和auther_obj2
book_obj1.auther.set([auther_obj1,auther_obj2])
book_obj2.auther.set([auther_obj1,auther_obj2])
#为书本2添加一个作者auther_obj3
book_obj2.auther.add(auther_obj3)
auther:作者表:
id | name |
---|---|
1 | sally |
2 | muyi |
3 | ying |
book:书本表
id | title |
---|---|
1 | sally_book1 |
2 | sally_book2 |
book_auther:关联表
id | book_id | auther_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 1 |
4 | 2 | 2 |
5 | 2 | 3 |
python
#查询数据
models.Auther.objects.create(name='sally')
auther_obj1=models.Auther.objects.filter(name='sally').first()
#查询作者sally有几本书,books为models中的related_name
print(auther_obj1.books为.all())
#查询书本'sally_book1'有几个作者
book_obj1=models.Book.objects.filter(title='sally_book1').first()
print(book_obj1.auther.all())