django多对多关系:如何删除项目但不从相关模型中删除它们

时间:2012-02-26 02:10:55

标签: django django-models

Django新手问题。我有以下型号:

class Leg(models.Model):
  drive_date = models.DateField()
  startpoint = models.CharField(max_length=50)
  endpoint = models.CharField(max_length=50)
  start_time = models.TimeField()
  riders = models.ManyToManyField(Rider, blank=True)
  drivers = models.ManyToManyField(Driver, blank=True)
  carpool = models.ForeignKey(Carpool,  blank=True, null=True)

对于Leg的某些实例,我想从Leg模型中删除任何现有的骑手和驱动程序,但不要分别从Rider或Driver Models(未显示)中删除它们。无法弄清楚该怎么做。当我迭代:

for driver in leg.drivers.all():
    driver.delete()

它似乎删除了我不想做的实际Driver对象。

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:12)

从关系中删除项目的正确代码是:

for driver in leg.drivers.all():
    leg.drivers.remove( driver )

答案 1 :(得分:1)

我可能采用的一种方法是为Driver模型创建自定义管理器。未经测试的代码如下:

from django.db import models

class DriverManager(models.Manager):
    def get_query_set(self):
        return super(DriverManager, self).get_query_set().filter(removed=False)

class Driver(models.Model):
    # new stuff to add ...
    removed = models.BooleanField(default=False)
    objects = models.Manager()  # default manager
    active = DriverManager()  # custom manager

说明:新的字段removed被添加到Driver模型中。您可以将其设置为True并保存,而不是删除记录。然后,在通常过滤Driver.objects的位置,请使用Driver.active。

答案 2 :(得分:0)

这样做

leg.drivers.clear()

.clear() to completely remove completely(efficiently)
.remove(<related obj>) to remove one relation
.remove([<related obj>, <related obj>...]) to remove one or more relation