Login

Field map for models

Author:
tomzee
Posted:
December 26, 2007
Language:
Python
Version:
.96
Tags:
models fields meta
Score:
1 (after 1 ratings)

It seems like one way or another I always need to get access to a specific field of a Model object. The current way to do this is to iterate through the object's _meta.fields list, comparing with the name attribute. Why not just have a lookup of fields? If you paste this code at the bottom of your models.py file it will add a field_map attribute to the meta options.

For example:

`profile = User.objects.get(id=1).get_profile()`
`upload_to = profile._meta.field_map['image_icon'].upload_to`
...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
################################################################################
try:
    import models as this_db
    for item in dir(this_db):
        try:
            obj = getattr(this_db, item)
            if type(obj) == models.base.ModelBase:
                fields = dict((f.name, f) for f in obj._meta.fields)
                setattr(obj._meta, 'field_map', fields)
        except:{}
except:{}
################################################################################

More like this

  1. Add model form field meta data in a DRY way by jedie 6 years ago
  2. Class ModelInfo for show object info by marinho 6 years, 9 months ago
  3. Human readable file names decorator by maxk 3 years, 12 months ago
  4. Username form field by sma 6 years, 4 months ago
  5. PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method by gnrfan 2 years, 10 months ago

Comments

Gulopine (on December 26, 2007):

Or you could just use _meta.get_field("name"), which has been available since Django's initial public release.

#

Please login first before commenting.