2013-09-01 39 views
1

我有以下模型屬性。所以我增加了一個@property「is_current」:Django的訪問模式,從經理

@property 
def is_current(self): 
    today = date.today() 
    if self.date_in and self.date_out: 
     if self.date_in <= today and self.date_out >= today: 
      return True 
    if self.date_in and not self.date_out: 
     if self.date_in <= today: 
      return True 

當試圖但是調用從過濾器的屬性在我的views.py,我得到以下錯誤,但:*無法解析關鍵字「is_current」到現場。選擇是:date_in,date_out,id,patient,room *

然後我想我可以用Manager來做到這一點。所以我增加了一個經理:

class Hospitalization(models.Model): 
    def get_query_set(self): 
     today = date.today() 
     if self.date_in and self.date_out: 
      return qs.filter(date_in__lte=today, date_out__gte=today) 
     if self.date_in and not self.date_out: 
      return qs.filter(date_in__lte=today) 

但是,這並不工作之一:* AttributeError的:「HospitalizationManager」對象有「date_in」沒有屬性*

是什麼Django的推薦的方式解決這一問題?

+0

是'如果真的self.date_in'必要的,如果date_in不能爲空的定義是什麼? – mariodev

+0

它不是。 :-)使用Q對象我能夠實現我想要的。謝謝@asermax。 – SaeX

回答

3

有各種各樣的東西不對您的Manager

  • 你繼承Model,不Manager
  • 您使用的模型屬性好像屬於Manager,,它們不是
  • 您的自定義get_queryset未調用超類方法,因此它使用未定義的qs屬性。

正確的方式來定義你的經理是:

class CurrentHospitalizationManager(models.Manager): 
    def get_query_set(self): 
     qs = super(CurrentHospitalizationManager, self).get_query_set() 
     today = date.today()  
     return qs.filter(
      # we can use Q objects here to check if the date_out exists or not 
      # and compare against the current date if necesary 
      models.Q(date_out__isnull=True) | models.Q(date_out__gte=today), 
      date_in__lte=today     
     ) 

那麼你應該將經理分配給你的模型類屬性,這樣

class Hospitalization(models.Model): 
    current_objects = CurrentHospitalizationManager() 
    ... 

而且在使用它你的代碼是這樣的:

Hospitalization.current_objects.get(...) # or filter, or whatever 

我不建議將此自定義管理器分配給您的默認管理器attr(objects),因爲您無法訪問Hospitalization的非「最新」實例。

Custom Manager's documentation

+0

感謝您的意見。我以前從未與Q合作過。 但是,似乎沒有工作,但只要我在qs.filter()中組合'date_in__lte = today'(如示例中所示),然後我得到一個'SyntaxError:non-keyword arg關鍵字參數「在模型的驗證。 – SaeX

+0

該問題似乎與filter()中兩個參數之間的逗號有關。我通過鏈接兩個過濾器來解決這個問題:'return qs.filter(date_in__lte = today).filter(models.Q(date_out__isnull = True)| models.Q(date_out__gte = today))''。謝謝! – SaeX

+0

如果有人有類似的問題,還有兩個補充:'get_queryset()'應該是'get_query_set()','super(HospitalizationManager,self)'應該是'超級(CurrentHospitalizationManager,self)'。 – SaeX