1 # -*- coding:utf-8 -*-
2 # 没法贴链接,参考自 CSDN:shangliuyan,好像没法贴链接,打出名字特此感谢,如有问题请留
3 from django.db import models
4
5
6 # 主表
7 class Author(models.Model):
8 first_name = models.CharField(max_length=30)
9 last_name = models.CharField(max_length=40)
10 email = models.EmailField()
11
12
13 # 从表
14 class Book(models.Model):
15 title = models.CharField(max_length=200)
16 authors = models.ManyToManyField(Author)
17
18 # 从表查主表
19 b = Book.objects.get(id=50)
20 b.authors.all()
21 b.authors.filter(first_name=‘Adam‘)
22
23 # 主表查从表
24 a = Author.objects.get(id=1)
25 a.book_set.all()
26
27 # 添加对象
28 a = Author.objects.get(id=1)
29 b = Book.objects.get(id=50)
30 b.authors.add(a)
31
32 # 删除对象
33 a = Author.objects.get(id=1)
34 b = Book.objects.get(id=50)
35 b.authors.remove(a) 或者 b.authors.filter(id=1).delete()