我有可以翻译的slug字段的模型,在每个模型中我都在编写相同的代码来执行以下操作:
def save(self, *args, **kwargs):
for lang_code, lang_verbose in settings.LANGUAGES:
if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'name_%s' % lang_code):
trans = getattr(self, 'name_%s' % lang_code, u"")
if not trans:
trans = self.name_en
setattr(self, 'slug_%s' % lang_code, slugify(trans))
super(Model, self).save(*args, **kwargs)
我试图在这些模型上摆脱相同的代码。我想使用一个抽象的父类,并继承自models.Model。我写道:
class ModelSluggable(models.Model):
#I also need to pass the fromField parameter to the parent class from child
def __init__(self, fromField):
super(SlugWithTrans,self).__init__(fromField)
slug = models.SlugField(editable=False, max_length=200, db_index=True)
class Meta:
abstract = True
def save(self, *args, **kwargs):
for lang_code, lang_verbose in settings.LANGUAGES:
if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'name_%s' % lang_code):
trans = getattr(self, 'name_%s' % lang_code, u"")
if not trans:
trans = self.name_en
setattr(self, 'slug_%s' % lang_code, slugify(trans))
super(SlugWithTrans, self).save(*args, **kwargs)
这是正确的方法吗?