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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。