How do I access a field's verbose_name?

858 views
Skip to first unread message

Jeff Blaine

unread,
Jun 20, 2011, 11:54:14 AM6/20/11
to django...@googlegroups.com
I'd like to make use of a field's verbose_name in some code instead of
duplicating that sort of info.  Can someone show me how?

Shawn Milochik

unread,
Jun 20, 2011, 11:56:00 AM6/20/11
to django...@googlegroups.com
On 06/20/2011 11:54 AM, Jeff Blaine wrote:
> I'd like to make use of a field's verbose_name in some code instead of
> duplicating that sort of info. Can someone show me how?
>

your_object._meta.verbose_name

Check out _meta in manage.py shell -- lots of good stuff in there.

Jeff Blaine

unread,
Jun 20, 2011, 1:36:00 PM6/20/11
to django...@googlegroups.com
That's the model's verbose_name

I want a field's verbose_name (see subject)

[ Thanks for replying though ]

Shawn Milochik

unread,
Jun 20, 2011, 1:50:48 PM6/20/11
to django...@googlegroups.com
Oops, I missed that. Still, my 'check out _meta' advice was spot on -- you can get the field verbose name from in there. Have you had a look at the things available in the _meta of your model? Hint, try get_field_by_name. I found it just now digging in there.

If there's an easier/cleaner way I hope someone else pipes in and mentions it.

Shawn




Kirill Spitsin

unread,
Jun 20, 2011, 3:08:59 PM6/20/11
to django...@googlegroups.com
On Mon, Jun 20, 2011 at 08:54:14AM -0700, Jeff Blaine wrote:
> I'd like to make use of a field's verbose_name in some code instead of
> duplicating that sort of info. Can someone show me how?

>>> SomeModel._meta.get_field(field_name).verbose_name

--
Kirill Spitsin

Jeff Blaine

unread,
Jun 20, 2011, 5:07:54 PM6/20/11
to django...@googlegroups.com
Thanks all.

For anyone coming across this later, some enlightening noodling.  All sorts of good
stuff in there, as Shawn indicated!

>>> from hostdb.models import Device
>>> dir(Device._meta)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_field_cache', '_field_name_cache', '_fields', '_fill_fields_cache', '_fill_m2m_cache', '_fill_related_many_to_many_cache', '_fill_related_objects_cache', '_join_cache', '_m2m_cache', '_many_to_many', '_name_map', '_prepare', '_related_many_to_many_cache', '_related_objects_cache', 'abstract', 'abstract_managers', 'add_field', 'add_virtual_field', 'admin', 'app_label', 'auto_created', 'auto_field', 'concrete_managers', 'contribute_to_class', 'db_table', 'db_tablespace', 'duplicate_targets', 'fields', 'get_add_permission', 'get_all_field_names', 'get_all_related_m2m_objects_with_model', 'get_all_related_many_to_many_objects', 'get_all_related_objects', 'get_all_related_objects_with_model', 'get_ancestor_link', 'get_base_chain', 'get_change_permission', 'get_delete_permission', 'get_field', 'get_field_by_name', 'get_fields_with_model', 'get_latest_by', 'get_m2m_with_model', 'get_ordered_objects', 'get_parent_list', 'has_auto_field', 'init_name_map', 'installed', 'local_fields', 'local_many_to_many', 'managed', 'many_to_many', 'module_name', 'object_name', 'order_with_respect_to', 'ordering', 'parents', 'permissions', 'pk', 'pk_index', 'proxy', 'proxy_for_model', 'related_fkey_lookups', 'setup_pk', 'setup_proxy', 'unique_together', 'verbose_name', 'verbose_name_plural', 'verbose_name_raw', 'virtual_fields']
>>> type(Device._meta.fields[0])
<class 'django.db.models.fields.AutoField'>
>>> type(Device._meta.fields[13])
<class 'django.db.models.fields.PositiveIntegerField'>
>>> Device._meta.fields[13].verbose_name
'Cores per Processor'
>>> Device._meta.get_field('cores_per_proc')
<django.db.models.fields.PositiveIntegerField object at 0xa7af50>
>>> Device._meta.get_field('cores_per_proc').verbose_name
'Cores per Processor'
>>> Device._meta.pk.name
'id'
>>> Device._meta.many_to_many
[<django.db.models.fields.related.ManyToManyField object at 0xabb150>, <django.db.models.fields.related.ManyToManyField object at 0xabb1d0>]
>>> for i in Device._meta.many_to_many: print i.name
...
tags
netgroups
>>>

Jeff Blaine

unread,
Jun 20, 2011, 6:09:55 PM6/20/11
to django...@googlegroups.com
Here's what I came up with, in case someone else finds this useful.

I'm quite proud, actually.

from django.core.management.base import BaseCommand, CommandError
from hostdb.models import Device, Interface

def sanitized_value(v):
    if v == None:
        return ""
    return v

class Command(BaseCommand):
    args = '<hostname1 hostname2...>'
    help = 'Display host information for the specified host(s)'

    def handle(self, *args, **options):
        for hostname in args:
            if hostname.find('.mitre.org') == -1:
                hostname = hostname + '.mitre.org'
            try:
                dev = Interface.objects.get(fqdn=hostname).device
            except Device.DoesNotExist:
                raise CommandError('Host "%s" does not exist' % hostname)

        # pk, the object defining the primary key of our model
        pk = Device._meta.pk

        # We turn this on because we know in our case our pk is "id"
        # which is pointless to print out in this context
        skip_pk = True

        # Iterate over all field objects (ManyToMany are not included
        # in this for some reason), in the order they are defined
        # in the model (thankfully!).
        for field in Device._meta.fields:
            if (field == pk) and skip_pk: continue
            vname = field.verbose_name
            val = sanitized_value(field.value_from_object(dev))
            self.stdout.write("%s: %s\n" % (vname, val))

        # Now handle the ManyToMany fields
        for field in dev._meta.many_to_many:
            m2m_manager = getattr(dev, field.name)
            vname = field.verbose_name
            l = []
            # Using ','.join(m2m_manager.all()) doesn't work because
            # ManyRelatedManager objects are not iterable.  We have to do this.
            for t in m2m_manager.all():
                l.append(str(t))
            val = ','.join(l)
            self.stdout.write("%s: %s\n" % (vname, val))

Reply all
Reply to author
Forward
0 new messages