# -*- coding:utf-8 -*-
# 沒法貼鏈接,參考自 CSDN:shangliuyan,好像沒法貼鏈接,打出名字特此感謝,如有問題請留
from django.db import models
# 主表
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)
# 從表查主表
b = Book.objects.get(id=50)
b.authors.all()
b.authors.filter(first_name='Adam')
# 主表查從表
a = Author.objects.get(id=1)
a.book_set.all()
# 添加對象
a = Author.objects.get(id=1)
b = Book.objects.get(id=50)
b.authors.add(a)
# 刪除對象
a = Author.objects.get(id=1)
b = Book.objects.get(id=50)
b.authors.remove(a) 或者 b.authors.filter(id=1).delete()