views:

181

answers:

3

Hi, I've this django model:

from django.db import models

class MyModel(models.Model):
    foo_it = model.CharField(max_length=100)
    foo_en = model.CharField(max_length=100)

    def save(self):
        print_all_field_starting_with('foo_')
        super(MyModel, self).save()

So I want to get all field starting with foo (as an example) and do something with this. I can't do this in the code because I don't know all fields from model (I'm using django-transmeta)

so, how can I do this?

Thanks in advance ;)

+2  A: 

You can do:

for field in dir(self):
    if field.startswith('foo_'):
      # getting with getattr(self, field)
      # setting with setattr(self, field, value)

If you want to get the list of fields you can also so this:

foo_fields = [field for field in dir(self) if field.startswith('foo_')]

Or print a list of values of foo fields:

print map(lambda x: getattr(self, x), [field for field in dir(self) if field.startswith('foo_')])
Felix Kling
Thanks this works :D
patrick
+2  A: 

This will do the trick, though you need to also pass in the object whose fields you want to print:

import inspect
def print_all_field_starting_with(prefix, object):
    for name, value in inspect.getmembers(object):
        if name.startswith(prefix):
            print name # or do something else

See the documentation for the inspect module for more info.

Will McCutchen
Thanks ;) I'll use this :)
patrick
No, it doesn't work :( I get an error: Manager isn't accessible via Post instance. Thanks however.
patrick
+2  A: 

There is a get_all_field_names() method that is built into the Meta subclass for all models, and can be found in foo._meta.get_all_field_names():

>>> from foo.models import Foo
>>> f = Foo.objects.get(pk=1)
>>> f._meta.get_all_field_names()
['active', 'created', 'expires', 'id', , 'inputter', 'reason', 'requester', 'updated']

So this would be a simple thing:

def print_all_fields_starting_with(obj, starter):
    fields = [x for x in obj._meta.get_all_field_names() if x.startswith(starter)]
    for field in fields:
        print getattr(obj, field)

And in your custom save():

def save(self):
    print_all_fields_starting_with(self, "foo_")
    super(MyModel, self).save()
jathanism
Cool! Nice solution :D Thanks ;)
patrick