如何过滤多对多字段的模型?

Du *_* D. 6 python django many-to-many model

我正在尝试为一队卡车实施地理围栏.我必须将边界列表与车辆相关联.除此之外,其中一个要求是,为了审计目的,删除所有内容甚至一旦删除.因此,我们必须对所有内容实施软删除.这就是问题所在.我的多对多字段不符合软删除管理器,它包括查找数据集中的活动和非活动记录.

class Vehicle(SoftDeleteModel):
    routes = models.ManyToManyField('RouteBoundary', through='VehicleBoundaryMap', verbose_name=_('routes'),
                                    limit_choices_to={'active': True})


class VehicleBoundaryMap(SoftDeleteModel):
    vehicle = models.ForeignKey(Vehicle, verbose_name="vehicle")
    route_boundary = models.ForeignKey(RouteBoundary, verbose_name="route boundary")
    # ... more stuff here

    alive = SoftDeleteManager()


class SoftDeleteManager(models.Manager):

    use_for_related_fields = True

    def get_queryset(self):
        return SoftDeleteQuerySet(self.model).filter(active=True)
Run Code Online (Sandbox Code Playgroud)

如上所示,我试图确保默认管理器是一个软删除管理器(即仅用于活动记录的过滤器),并尝试使用limit limit_choices_to但结果只是对外部模型进行了字段而不是我想要的"直通"模型.如果您有任何建议或建议,我很乐意听取您的意见.

谢谢!

Lou*_*uis 5

第一个问题:你的使用limit_choices_to不起作用,因为文档说:

limit_choices_to在使用参数ManyToManyField指定的自定义中间表上使用时无效through.

你这样使用throughlimit_choices_to没有效果的.

第二个问题:你的使用use_for_related_fields = True也是无效的.该文件说,关于这个属性:

如果在模型的默认管理器上设置了此属性(在这些情况下仅考虑默认管理器),Django将在需要自动为类创建管理器时使用该类.

您的自定义管理器被分配给alive属性VehicleBoundaryMap而不是objects被忽略.

我认为哪种方式可行的方法是:

  1. 为其创建代理模型VehicleBoundaryMap.我们称之为VehicleBoundaryMapProxy.设置它以使其默认管理器为SoftDeleteManager():

    class VehicleBoundaryMapProxy(VehicleBoundaryMap):
        class Meta:
            proxy = True
    
        objects = SoftDeleteManager()
    
    Run Code Online (Sandbox Code Playgroud)
  2. through='VehicleBounddaryMapProxy'你的ManyToManyField:

     class Vehicle(SoftDeleteModel):
        routes = models.ManyToManyField('RouteBoundary', 
                                         through='VehicleBoundaryMapProxy', 
                                         verbose_name=_('routes'))
    
    Run Code Online (Sandbox Code Playgroud)