Vitalii Ponomar
Vitalii Ponomar

Reputation: 10936

Django: how to use Model properties as a string?

Supose I have such Model:

class MyModel(models.Model):
    var1 = models.CharField(max_length=10)
    var2 = models.CharField(max_length=10)
    var3 = models.CharField(max_length=10)
    var4 = models.CharField(max_length=10)
    ...
    var100 = models.CharField(max_length=10)

I must process all them in similar way, for example:

string = var1 if var1 else ''
string += var2 if var2 else ''
string += var3 if var3 else ''
string += var4 if var4 else ''
...
string += var100 if var100 else ''

In such way I will write 100 hundreds lines of code...

But maybe there is some way to process all of them in for statement, like:

string = ''
for i in range(1,101):
    string += var%s % i if var%s % i else '': #I know this is not right, but idea is understood

So I will write only 3 lines of code.

Is it possible do in Django?

Thanks!

Upvotes: 0

Views: 129

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Use getattr to access the attributes in code

>>> class MyModel():
...    var1 = 'hello'
...    var2 = 'there'
...    var3 = 'simple'
...    var4 = 'example'
...
>>> foo = MyModel()
>>> getattr(foo,'var1')
'hello'
>>> number = 3
>>> getattr(foo,'var%s'%number)
'simple'
>>> for x in range(1,5):
...   print getattr(foo,'var%s' % x)
...
hello
there
simple
example

Upvotes: 0

Tiago
Tiago

Reputation: 9557

You could you try this:

#assuming this is on the Model
def get_values(self):
    ret = []
    for i in range(1, 101):
        field_name = "var%d" % i
        value = self._meta.get_field(field_name).value_from_object(self)
        if value:
            ret.append(value)

    return ''.join(ret)

Upvotes: 2

Related Questions