Login

Field map for models

Author:
tomzee
Posted:
December 26, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.