Django -- 多对多建表增删改查

ManyToManyField -- 自动创建第三张对应关系表

表结构

class Author(models.Model):
    name = models.CharField(max_length=32)
    books = models.ManyToManyField('Book')   # 描述多对多关系,不生成字段,生成关系表

 

查询

 def author_list(request):
    all_author = models.Author.objects.all()
    for author in all_author:
        print(author)  # Author object
        print(author.pk)  # 1 -- 数据对象ID
        print(author.name)  # 小白 -- 数据对象name
        print(author.books)  # app01.Book.None 关系管理对象
        print(author.books.all())  # 所关联的所有对象 QuerySet列表

 

增加

def author_add(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        books = request.POST.getlist('books')  # getlist 获取多个元素
        author_obj = models.Author.objects.create(name=name) # 创建新作者
        author_obj.books.set(books) # 给作者和书籍绑定关系[id,id],写在author_book表中

 

删除

def author_del(request):
    pk = request.GET.get('pk')
    models.Author.objects.filter(pk=pk).delete()

 

编辑

def author_edit(request):
    pk = request.GET.get('pk')
    obj = models.Author.objects.filter(pk=pk).first()
    if request.method == 'POST':
        name = request.POST.get('name')
        books = request.POST.getlist('books')
​
        obj.name = name
        obj.save()
        obj.books.set(books)

 

 
posted on 2019-08-28 19:52  ShenQiang  阅读(169)  评论(0编辑  收藏  举报