时间:2021-07-01 10:21:17 帮助过:45人阅读
(一)获取对象方法:
1.从作者出发获取书籍
[python] view plain copy
- person = Person.objects.fiter(你的条件)
- book = person.book_set.all()
2.从书籍出发获取作者
[python] view plain copy
- p = book.person
例子:一个作者对应多本书,一本书有多个作者
model代码:
[python] view plain copy
- class Author(models.Model):
- first_name = models.CharField(max_length=30)
- last_name = models.CharField(max_length=40)
- email = models.EmailField()
- class Book(models.Model):
- title = models.CharField(max_length=200)
- authors = models.ManyToManyField(Author)
(一)获取对象方法:
1.从书籍出发获取作者
[python] view plain copy
- b = Book.objects.get(id=50)
- b.authors.all()
- b.authors.filter(first_name=‘Adam‘)
2.从作者出发获取书籍
[python] view plain copy
- a = Author.objects.get(id=1)
- a.book_set.all()
(二)添加对象方法:
[python] view plain copy
- a = Author.objects.get(id=1)
- b = Book.objects.get(id=50)
- b.authors.add(a)
(三)删除对象对象方法:
[python] view plain copy
- a = Author.objects.get(id=1)
- b = Book.objects.get(id=50)
- b.authors.remove(a) 或者 b.authors.filter(id=1).delete()
转: django数据库操作-增删改查-多对多关系以及一对多(外键)关系
标签:rem cts views 添加 作者 delete clipboard lock length