【发布时间】:2013-07-15 15:26:21
【问题描述】:
背景:我使用django-hvad 并拥有TranslatableModel。在其TranslatedFields 中,我有一个slug 属性,应该在保存模型时使用title 属性自动创建。
问题:在保存实例时很难设置TranslatedFields 之一的值。一个可行的解决方案是覆盖我的TranslatableModel 的save_translations 方法,如下所示。只有倒数第二行与原来的不同:
@classmethod
def save_translations(cls, instance, **kwargs):
"""
The following is copied an pasted from the TranslatableModel class.
"""
opts = cls._meta
if hasattr(instance, opts.translations_cache):
trans = getattr(instance, opts.translations_cache)
if not trans.master_id:
trans.master = instance
# The following line is different from the original.
trans.slug = defaultfilters.slugify(trans.title)
trans.save()
这个解决方案不好,因为它使用了复制和粘贴。有没有更好的方法来达到同样的效果?
【问题讨论】:
标签: django django-models translation django-hvad