在django中删除多对多对象

llmtgqce  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(122)

我有两个这样的模型:

class Toppings(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=300)

class Pizza(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=300)
    toppings =  models.ManyToManyField(Toppings)

我做了一个比萨饼然后加了这样的配料

crazy_pizza = Pizza(name = "crazy pizza")
crazy_pizza.save() 
toppings = ["pepperoni","chicken","bacon"]
for i in toppings:
    topping = Toppings(name = i)
    toppings.save()
    crazy_pizza.add(topping)
crazy_pizza.save()

现在我想删除所有与疯狂比萨相关的配料。

crazy_pizza.toppings.clear()

这将删除多对多的引用,我怎样才能同时删除所有实际的浇头对象呢?

相关问题