在我的Django项目中,用户删除的所有实体必须通过将当前日期时间设置为deleted_at属性进行软删除。我的模型看起来像这样:旅行< - > TripDestination < - >目的地(多对多关系)。换句话说,旅程可以有多个目的地。如何软删除与Django的多对多关系
当我删除一个Trip时,SoftDeleteManager会过滤掉所有被删除的行程。但是,如果我请求旅行的所有目的地(使用get_object_or_404(Trip,pk = id)),我也会得到已删除的目的地(即,带有deleted_at == null或deleted_at!= null的TripDestination模型)。我真的不明白为什么,因为我所有的模型都从LifeTimeTracking继承,并使用SoftDeleteManager。
有人可以帮我理解为什么SoftDeleteManager不适用于n:m关系吗?
class SoftDeleteManager(models.Manager):
def get_query_set(self):
query_set = super(SoftDeleteManager, self).get_query_set()
return query_set.filter(deleted_at__isnull = True)
class LifeTimeTrackingModel(models.Model):
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
deleted_at = models.DateTimeField(null = True)
objects = SoftDeleteManager()
all_objects = models.Manager()
class Meta:
abstract = True
class Destination(LifeTimeTrackingModel):
city_name = models.CharField(max_length = 45)
class Trip(LifeTimeTrackingModel):
name = models.CharField(max_length = 250)
destinations = models.ManyToManyField(Destination, through = 'TripDestination')
class TripDestination(LifeTimeTrackingModel):
trip = models.ForeignKey(Trip)
destination = models.ForeignKey(Destination)
分辨率 我提交的bug 17746在Django错误DB。感谢卡斯帕在这方面的帮助。
@Martin我已经更新了我的答案,请看看它是否适合你:) – Caspar 2012-02-22 01:44:44
你好卡斯帕!谢谢你的协助。但是我正在寻找的是如果Tripdesrimation已被删除,而不是目的地,则看不到目的地。 – Martin 2012-02-22 02:37:55
啊,我明白你的意思了。我试过了,它不能与我的解决方案一起工作,我认为这个解决方案指出了一个错误。通过bug数据库的[快速搜索](https://code.djangoproject.com/search?q=use_for_related_fields)并不能解决任何问题(尽管存在一个[几乎相反的问题](https:// code.djangoproject.com/ticket/14891)),那么可能是时候提出bug了。 – Caspar 2012-02-22 07:09:24