Django ORM 一对多,多对多 添加操作

模型类

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32, default=None)
    create_time = models.DateTimeField()
    price = models.DecimalField(decimal_places=2, max_digits=8, default=None)
    publish_id = models.ForeignKey(to="Publish", on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')

    def __str__(self):
        return str(self.nid) + ':' + self.title


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


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    email = models.CharField(max_length=32)
    ad = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    address = models.CharField(max_length=32)
    telephone = models.IntegerField()

一对多和多对多 添加操作

 # 一对多添加用户
    publish = Publish.objects.get(nid=1)
    Book.objects.create(
        title='ubuntu',
        price=122,
        create_time='2012-2-2',
        publish_id=publish,
        # publish_id_id=publish.nid
    )

    # 多对多添加用户
    author01 = Author.objects.get(id="1")
    author02 = Author.objects.get(id="2")
    book = Book.objects.get(nid='2')
    # book.authors.add(author01, author02)

    # 多对多第二种
    book.authors.add(1, 2)
    # 多对多第三种
    book.authors.add(*[1, 2])

    # 删除关联的作者
    book.authors.remove(author01)

    # 删除所有关联的作者
    book.authors.clear()

    # 先删除所有在绑定
    book.authors.set(1)

猜你喜欢

转载自www.cnblogs.com/ls1997/p/10970583.html