Django では、地理的オブジェクトのブレッドクラム (父親のリスト) を計算します。頻繁に変更されることはないので、オブジェクトが保存または初期化されたら、事前に計算することを考えています。
1.) 何が良いでしょうか? パフォーマンスが向上するソリューションはどれですか? ____init____で計算するか、オブジェクトが保存されたときに計算しますか(オブジェクトはDBで約500〜2000文字かかります)?
2.) ____init____ または save() メソッドを上書きしようとしましたが、保存したばかりのオブジェクトの属性を使用する方法がわかりません。*args、**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...
それが属性crumb()を計算する方法です
def _breadcrumb(self):
breadcrumb = [ ]
x = self
while True:
x = x.father
try:
if hasattr(x, 'country'):
breadcrumb.append(x.country)
elif hasattr(x, 'region'):
breadcrumb.append(x.region)
elif hasattr(x, 'city'):
breadcrumb.append(x.city)
else:
break
except:
break
breadcrumb.reverse()
return breadcrumb
それは私の保存方法です:
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)
私を助けてください。私はこれに何日も取り組んでいます。ありがとうございました。