2012-11-09 32 views
2

我試圖將一些功能邏輯到模型的方法(而不是在視圖)的Django模型的方法,在這裏我認爲它屬於:自例如

class Spans(models.Model): 
    snow = models.IntegerField() 
    wind = models.IntegerField() 
    exposure = models.CharField(max_length=1) 
    module_length = models.IntegerField() 
    max_roof_angle = models.IntegerField() 
    building_height = models.IntegerField() 
    importance_factor = models.IntegerField() 
    seismic = models.DecimalField(max_digits=4, decimal_places=2) 
    zone = models.IntegerField() 
    profile = models.CharField(max_length=55) 
    tilt_angle = models.IntegerField() 
    span = models.DecimalField(max_digits=18, decimal_places=15) 

    def get_spans(self, snow_load, wind_speed, module_length): 
     """ 
     Function to get spans. 
     """ 
     spans = self.objects.filter(
      snow=snow_load, 
      wind=wind_speed, 
      exposure='B', 
      module_length__gte=module_length, 
      max_roof_angle=45, 
      building_height=30, 
      importance_factor=1, 
      seismic=1.2, 
      zone=1, 
      profile='worst' 
     ).order_by('snow', 'module_length', 'span') 
     return spans 

不過,我有點不確定如何稱它。在shell我曾嘗試:

>>> possible_spans = Spans.get_spans(0, 85, 54) 

>>> possible_spans = Spans.get_spans(Spans, 0, 85, 54) 

,但我得到一個錯誤:

TypeError: unbound method get_spans() must be called with Spans instance as first argument (got int instance instead) 

TypeError: unbound method get_spans() must be called with Spans instance as first argument (got ModelBase instance instead) 

我知道我失去了一些東西根本在這裏的Python邏輯,但我不知道這是什麼。

任何幫助將不勝感激。

回答

4

方法需要與實例一起調用,因爲方法調用使其成爲默認的自我參數。例如,

instance = Spans.objects.get(id=1) 
instance.get_spans(0, 85, 54) 

或者如果你想使用類本身來調用。你將不得不通過實例手動

instance = Spans.objects.get(id=1) 
Spans.get_spans(instance, 0, 85, 54) 

更新: 什麼你正在尋找可以使用靜態方法

@staticmethod 
def get_spans(snow_load, wind_speed, module_length): 
     """ 
     Function to get spans. 
     """ 
     spans = Spans.objects.filter(
      snow=snow_load, 
      wind=wind_speed, 
      exposure='B', 
      module_length__gte=module_length, 
      max_roof_angle=45, 
      building_height=30, 
      importance_factor=1, 
      seismic=1.2, 
      zone=1, 
      profile='worst' 
     ).order_by('snow', 'module_length', 'span') 
     return spans 

現在你可以直接做來實現,

Spans.get_spans(0, 85, 54) 
+0

好 - 那麼這個函數畢竟可能不是一個模型方法。我實際上打算查詢整個Spans表以獲得'Spans'對象的query_set。 –

+0

我已經更新了我的答案,請查看 –

+0

Intresting。我以前沒有遇到過靜態方法。 –