2010-05-04 55 views
1

在Django中,我計算地理對象的麪包屑(父親列表)。由於它不會經常改變,所以我想在保存或初始化對象之前預先計算它。如何處理Django模型中的動態計算屬性?

1.)什麼會更好?哪種解決方案會有更好的性能?要在____init____計算它,或者在保存對象時計算它(該對象在數據庫中需要大約500-2000個字符)?

2.)我試圖覆蓋____init____或save()方法,但我不知道如何使用剛剛保存的對象的屬性。訪問*參數,** kwargs不起作用。我如何訪問它們?我必須保存,訪問父親然後再保存嗎?

3.)如果我決定保存麪包屑。最好的辦法是做什麼?我用http://www.djangosnippets.org/snippets/1694/並有crumb = PickledObjectField()。

型號:

class GeoObject(models.Model): 
    name = models.CharField('Name',max_length=30) 
    father = models.ForeignKey('self', related_name = 'geo_objects') 
    crumb = PickledObjectField() 
    # more attributes... 

那來計算屬性碎屑()方法

這就是我保存法:

def save(self,*args, **kwargs): 
    # how can I access the father ob the object? 
    father = self.father # does obviously not work 
    father = kwargs['father'] # does not work either 

    # the breadcrumb gets calculated here 
    self.crumb = self._breadcrumb(father) 
    super(GeoObject, self).save(*args,**kwargs) 

請幫助我。我現在正在爲此工作數天。謝謝。

+0

但什麼是「父親」?你說訪問'self.father' *顯然*不起作用,但爲什麼不呢?究竟是什麼? – 2010-05-04 08:09:48

+0

父親是模型中的一個屬性。我現在添加了模型的示例代碼。顯然,我的意思是,我無法訪問該對象,因爲它尚未保存。 – bullfish 2010-05-04 08:25:54

+0

完全沒有。如果你有一個父親(這裏通常的英文單詞是父母,但這並不重要),無論你是否已經保存,都可以訪問。如果你沒有一個,你的代碼中沒有設置一個,所以你保存後仍然沒有。 – 2010-05-04 10:18:12

回答

0

通過使用x.father調用_breadcrumb方法並在while循環的開頭分配x = x.father,可以跳過一個父親。嘗試更換

self.crumb = self._breadcrumb(father) 

self.crumb = self._breadcrumb(self) 

通過模型類中定義_breadcrumb你可以清理這樣的:

class GeoObject(models.Model): 
    name = models.CharField('Name',max_length=30) 
    father = models.ForeignKey('self', related_name = 'geo_objects') 
    crumb = PickledObjectField() 
    # more attributes... 

    def _breadcrumb(self): 
     ... 
     return breadcrumb 

    def save(self,*args, **kwargs): 
     self.crumb = self._breadcrumb() 
     super(GeoObject, self).save(*args,**kwargs) 

對於更復雜的hierachies我建議django-treebeard

+0

這是現在的工作。非常感謝 :) – bullfish 2010-05-04 21:40:45