Flask接口签名sign原理与实例代码浅析
412
2023-01-07
Django之多对多查询与操作方法详解
多对多表之间关系表
models.py文件代码
from django.db import models
# Create your models here.
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64,null=False,unique=True)
def __str__(self):
return "publisher_name:{}".format(self.name)
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=128,null=False)
publisher = models.ForeignKey(to=Publisher,related_name="books")
def __str__(self):
return "book_title:{}".format(self.title)
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=16,null=False)
book = models.ManyToManyField(to="Book")
def __str__(self):
return http://"author_name:{}".format(self.name)
查询与操作方法代码
import os
if __name__ == '__main__':
#加载Django项目的配置信息
os.environ.setdefault("DJANGO_SETTINGS_MODULE","testinclude.settings")
#导入Django,并启动Django项目
import django
django.setup()
from ormtest import models
#多对多查询
author_obj = models.Author.objects.get(name="小白")
print(author_obj)
author_obj_books = author_obj.book.all()
print(author_obj_books)
#首先:在book表中创建一本书,并指定相应的出版社
author_obj.book.create(title="zabbix从入门到精通",publisher_id=3)
book_obj = models.Book.objects.get(title="网络基础原理")
author_obj.book.add(book_obj)
book_obj = models.Book.objects.get(title="网络基础原理")
author_obj.book.remove(book_obj)
author_obj.book.remove(4)
author_obj.book.clear()
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~