如果我的模型包含许多具有默认值的字段,是否有任何方法可以配置字符串表示以仅显示非默认值。即:
from django.db import models
class Config(models.Model):
debug = models.IntegerField(default=7)
retry = models.BooleanField(default=True)
def __unicode__(self):
# here is where the magic would go
# if debug is at default value (7), do no show it, otherwise skip
config_str = ['generic config']
for field in self._meta.get_all_field_names():
config_str.append('%s=%s' % (field, getattr(self, field, None)))
return ' '.join(config_str)
这样str(Config(retry=True, debug=7))
为'generic config'
但str(Config(retry=True, debug=8))
为'generic config debug=8'
答案 0 :(得分:0)
这样的事似乎在做这项工作。如果有更好的方法可以告诉我:
def __unicode__(self):
config_details = ['generic config']
for field_name in self._meta.get_all_field_names():
# it is important to list all related objects here too,
# otherwise strange things may happen
if field_name in ('id', ):
continue
value = getattr(self, field_name, '')
default_value = self._meta.get_field(field_name).get_default()
if (value !=default_value):
det_str = '%s=%s' % (field_name, value)
config_details.append(det_str)
return ' '.join(config_details)