django模型的字符串表示,仅显示非默认模型字段

时间:2014-12-12 22:27:56

标签: django django-models

如果我的模型包含许多具有默认值的字段,是否有任何方法可以配置字符串表示以仅显示非默认值。即:

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'

1 个答案:

答案 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)