• 周二. 9月 27th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Django ORM多表操作实际例子增删改查

admin

11月 28, 2021

编写例子,代码如下

class Book(models.Model):   #意见
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish = models.ForeignKey(to="Publish", to_field="pid", on_delete=models.CASCADE)
    author = models.ManyToManyField(to="Author")


class Publish(models.Model):
    pid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)


class Author(models.Model):
    aid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to="Author_detail", to_field="aid", on_delete=models.CASCADE)


class Author_detail(models.Model):  # 已建
    aid = models.AutoField(primary_key=True)
    add = models.CharField(max_length=32)
    city = models.CharField(max_length=32)

对应关系图如下:

多表之增加 代码示例


    models.Publish.objects.create(name="南京出版社")
    models.Publish.objects.create(name="北京出版社")
    models.Publish.objects.create(name="浙江出版社")

    # 新增作者详情表  Author_detail
    models.Author_detail.objects.create(add="鄞州区", city="宁波市")
    models.Author_detail.objects.create(add="余姚区", city="余姚市")
    models.Author_detail.objects.create(add="奉化区", city="奉化市")
    models.Author_detail.objects.create(add="温州区", city="温州市")

    # 新增作者表  Author
    au_detail = models.Author_detail.objects.filter(city="余姚市").first()
    au = models.Author.objects.create(name="blex", age=28, author_detail=au_detail)
    au = models.Author.objects.create(name="clex", age=38, author_detail_id=3)
    au = models.Author.objects.create(name="alex", age=18, author_detail_id=1)

    # 新增书籍表 Book
    pub = models.Publish.objects.filter(name="南京出版社").first()
    bk1 = models.Book.objects.create(title="python", price=18.23, publish_id=2)
    bk2 = models.Book.objects.create(title="java", price=28.23, publish=pub)

    # 新增书籍和作者多对多关系表  Book_author
    alex = models.Author.objects.filter(name="alex").first()
    blex = models.Author.objects.filter(name="blex").first()
    bk_author1 = bk1.author.add(*[alex, blex])
    bk_author2 = bk2.author.add(alex, blex)
    # 就是移除book title 是java的id,和author表id为1 的关联
    bk2.author.remove(1)
    # 就是移除book title 是java的id,和author表中alex,blex 的关联
    bk2.author.remove(*[alex, blex])
    # clear方法没有参数,会移出所有和java id关联的作者数据
    bk2.author.clear()
    # all这个方法可以查询多表关系中所有对应java这本书的作者
    bk = models.Book.objects.filter(title="java").first()
    print(bk.author.all())

发表回复

您的电子邮箱地址不会被公开。