簡體   English   中英

繞過自定義模型管理器以獲取ManyToMany對象

[英]Bypassing custom Model Manager to get ManyToMany objects

我正在一個維護項目中,該項目的模型為“ Business”和一個自定義Model Manager。 這個自定義的模型管理器為在業務模型上執行的所有查詢添加了一些額外的過濾器。 此業務模型有一個自稱為Trainers的ManyToMany字段。 到目前為止,當我嘗試在不應用這些過濾器的情況下嘗試獲取與業務相關的所有培訓師時,就會出現問題。

業務模型如下:

class Business(Basetable):
    #status P=publish    H=inactive    D=draft    N=new
    name = models.CharField(max_length=120)
    slug = models.SlugField(max_length=150)
    logo=models.OneToOneField("BusinessLogo",null=True,on_delete=models.SET_NULL)
    categories = models.ManyToManyField("BusinessCategory",related_name='allcategories',null=True)
    price_type = models.CharField(max_length=2,
                                      choices=PRICE_CHOICES,
                                      default=YEARLY, null=True, blank=True)
    achievements = models.TextField(null=True, blank=True)
    years_of_experience = models.FloatField(null=True, blank=True)

    trainers = models.ManyToManyField("self",related_name='btrainers',null=True, blank=True, symmetrical=False)
    expense=models.IntegerField(null=True,blank=True)
    objects= CityManager()

    def get_trainers(self):
      return self.trainers.all()

get_trainers是返回與業務相關聯的所有培訓師的函數,但是我希望結果繞過CityManager並使用默認的Manager。

任何指針將不勝感激。

更新:

使用use_for_related_fields = False無效。 我在這里找到了一個相關的錯誤 有沒有解決的辦法? 我知道重寫默認objects不是一個好習慣,但這是我收到的。

通常,最好避免在默認的Manager 過濾結果

最好謹慎選擇默認管理器,以避免覆蓋get_queryset()導致無法檢索要使用的對象的情況。

但是,如果由於向后兼容的原因而不能更改默認Manager ,則仍然可以顯式創建一個普通Manager並使用該結果獲取結果。

class Business(Basetable):
    ...
    objects = CityManager()  # Still the first listed, and default
    plain_objects = models.Manager()

現在您有了一個普通的Manager ,使用它可以顯式訪問所需的對象:

def get_trainers(self):
    return Business.plain_objects.filter(btrainers__id=self.id)

暫無
暫無

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

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