是否有可能在Django中使用多个对象描述?
问题描述:
在模型类,我们可以定义个对象描述是否有可能在Django中使用多个对象描述?
def __unicode__(self):
return u'%s %s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual, "Description:" , self.description)
但有时我需要在不同情况下有不同的描述。 是否有可能为Django中的同一对象维护多种描述格式?
答
你可以决定它里面__unicode__
像这样:
def __unicode__(self):
# If the description of the object is empty, for example:
if self.description == "":
return u'%s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual)
return u'%s %s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual, "Description:" , self.description)
+0
所以它将由对象本身驱动,而不是从我称之为的地方驱动。 –
答
你不应该依赖比基本表示其他任何内容__str__
或__unicode__
方法。对于任何更复杂的情况,请在其他地方执行 - 例如在模板或其他代码中。
答
你可以这样做:
class Example(models.Model):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
if self.description == "":
self._desc = u'%s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual)
else:
self._desc = u'%s %s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual, "Description:" , self.description)
def __unicode__(self):
return self._desc
你怎么会告诉Django使用哪个描述是什么时候?您可以定义自己的方法并在需要的上下文中调用它们。例如。 'def my_context_description(self):return u'%s'%(self.id)' – dirkgroten