如何处理Django模型中的动态计算属性?
在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)
请帮助我。我现在正在为此工作数天。谢谢。
通过使用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
这是现在的工作。非常感谢 :) – bullfish 2010-05-04 21:40:45
但什么是“父亲”?你说访问'self.father' *显然*不起作用,但为什么不呢?究竟是什么? – 2010-05-04 08:09:48
父亲是模型中的一个属性。我现在添加了模型的示例代码。显然,我的意思是,我无法访问该对象,因为它尚未保存。 – bullfish 2010-05-04 08:25:54
完全没有。如果你有一个父亲(这里通常的英文单词是父母,但这并不重要),无论你是否已经保存,都可以访问。如果你没有一个,你的代码中没有设置一个,所以你保存后仍然没有。 – 2010-05-04 10:18:12