簡體   English   中英

如何過濾多對多字段的模型?

[英]How to filter through Model of a many-to-many field?

我正在嘗試為一隊卡車實施地理圍欄。 我必須將邊界列表與車輛相關聯。 除此之外,其中一個要求是,為了審計目的,刪除所有內容甚至一旦刪除。 因此,我們必須對所有內容實施軟刪除。 這就是問題所在。 我的多對多字段不符合軟刪除管理器,它包括查找數據集中的活動和非活動記錄。

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)

如上所示,我試圖確保默認管理器是一個軟刪除管理器(即僅用於活動記錄的過濾器),並嘗試使用limit limit_choices_to但結果只是對外部模型進行字段而不是我想要的“直通”模型。 如果您有任何建議或建議,我很樂意聽取您的意見。

謝謝!

第一個問題:你使用limit_choices_to將無法正常工作,因為文檔說

limit_choices_to具有使用through參數指定的自定義中間表的ManyToManyField上使用limit_choices_to時無效。

您正在使用through因此limit_choices_to無效。

第二個問題:你使用use_for_related_fields = True也是無效的。 文檔說明了這個屬性:

如果在模型的默認管理器上設置了此屬性(在這些情況下僅考慮默認管理器),Django將在需要自動為類創建管理器時使用該類。

您的自定義管理器被分配給VehicleBoundaryMapalive屬性而不是objects因此將被忽略。

我認為可行的一種方式是:

  1. VehicleBoundaryMap創建代理模型 我們稱之為VehicleBoundaryMapProxy 設置它以使其默認管理器是SoftDeleteManager()類似於:

     class VehicleBoundaryMapProxy(VehicleBoundaryMap): class Meta: proxy = True objects = SoftDeleteManager() 
  2. ManyToManyFieldthrough='VehicleBounddaryMapProxy'

      class Vehicle(SoftDeleteModel): routes = models.ManyToManyField('RouteBoundary', through='VehicleBoundaryMapProxy', verbose_name=_('routes')) 

如果你這樣做怎么辦:

class Vehicle(SoftDeleteModel):
    #you can even remove that field
    #routes = models.ManyToManyField('RouteBoundary', through='VehicleBoundaryMap', verbose_name=_('routes'),
    #                                limit_choices_to={'active': True})

    @property
    def routes(self):
        return RouteBoundary.objects.filter(
            vehicleboundarymap__active=True,
            vehicleboundarymap__vehicle=self,
        )

而現在,而不是vehicle.routes.clear()使用vehicle.vehicleboundarymap_set.delete() 您將只會失去反向關系( RouteBoundary.vehicles ),但您可以使用相同的方式實現它。

由於中間模型,其余的M2M field特征無論如何都被禁用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM