Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing model field attributes in Django

I have a model in Django 1.2.4:

class MyModel():
    foo = IntegerField(verbose_name="bar")

    def printFoo(self):
        print("Value of %s is %d" % (foo.verbose_name, foo))

I'm trying to get both the value and verbose name of a field. How can I do this?

I've looked at myModel._meta.fields, but I'm not sure if that's the way to go.

like image 321
Nick Heiner Avatar asked Jan 10 '11 20:01

Nick Heiner


People also ask

What is Verbose_name in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.

What is Related_name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")


1 Answers

Probably like this:

MyModel._meta.get_field('foo').verbose_name

See How can I programmatically obtain the max_length of a Django model field? for a very similar question.

like image 140
Ben James Avatar answered Oct 12 '22 17:10

Ben James