简体   繁体   English

循环浏览Django中的模型并默认获取列名和.get_FOO_display

[英]Looping through models in Django and getting column names and .get_FOO_display by default

I have the following: 我有以下几点:

# model

TITLE_CHOICES = (
    ('mr', 'Mr.'),
    ('ms', 'Ms.'),
    ('mrs', 'Mrs.'),
    ('mis', 'Miss.'),
)
class Client(models.Model):
    name_title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)

# form
class ClientForm(ModelForm):
    class Meta:
        class = Client

# view
def client_view(request):
    client = Client.object.get(id=1)
    clientForm = ClientForm(instance=client)
    return render_to_response('client.html',{'client':client,
                                             'clientForm':clientForm}, ...)

# client.html
...

How can I loop through the object client printing out the column name and the value while making sure that if the value is a choice it prints out the human-readable choice value, not the stored value ( get_title_display )? 如何遍历对象client打印出列名和值,同时确保如果值是choice则打印出人类可读的选项值,而不是存储的值( get_title_display )?

And why is this not eaiser to do in Django? 为什么在Django中不那么轻松呢? (isn't this a common thing to want do?) (这不是常见的事情吗?)

If I can't do this I have to go statically through each column and use get_title_display , which means that there is no separation between model and template, which means if I change my model I have to manually update the template(s). 如果无法执行此操作,则必须静态浏览每列,并使用get_title_display ,这意味着模型和模板之间没有分隔,这意味着如果更改模型,则必须手动更新模板。 This is not good 不是很好

Try something like: 尝试类似:

# add to your Client model    
def get_fields(self):
    fields_display = []
    for f in Client._meta.fields:
        name = f.name        
        if len(f.choices) == 0:
            fields_display.append([name, f.value_to_string(self)])
        else:
            fields_display.append([name, getattr(self,"get_%s_display" % name)()])

   return fields_display

You can then loop over get_fields in your template for a given object 然后,您可以在模板中为给定对象遍历get_fields

If you want to get get_FOO_display by default, you have to overwrite the __getattribute__ method. 如果要默认获取get_FOO_display ,则必须覆盖__getattribute__方法。 Try something like this: 尝试这样的事情:

class FooModel(models.Model):
    ...
    def __getattribute__(self, item):
        get = lambda i: object.__getattribute__(self, i)
        name_map = get('_meta')._name_map

        if item.startswith('_') or name_map.has_key(item):
            return get(item)

        else:
            field = name_map.get(item)
            if field.choices:
                return get('get_%s_display' % item)()

            else:
                return get(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM