Dmitry
Dmitry

Reputation: 4373

django __str__ return all the attributes

Is there a way in django __str__ to output all attributes in one shot instead of doing one by one like I'm doing here? I'm planning to have about 100 attributes so putting all in the str method doesn't seem right.

class Carmodel(models.Model):
    year = models.PositiveSmallIntegerField(default=2016)
    make = models.CharField(max_length=60)
    model = models.CharField(max_length=60)
    styles = models.PositiveSmallIntegerField(default=1)

     def __str__(self):
         return '%s %s %s %s' % (self.year, self.make, self.model, self.styles)

Upvotes: 2

Views: 4324

Answers (3)

Sergei V Kim
Sergei V Kim

Reputation: 205

As of Django 1.10+ get_all_field_names is removed and now we have to use get_fields

Updated version looks like this:

def __str__(self):
    field_values = []
    for field in self._meta.get_fields():
        field_values.append(str(getattr(self, field.name, '')))
    return ' '.join(field_values)

Upvotes: 4

Shang Wang
Shang Wang

Reputation: 25539

I'm not sure if that's a good idea, but for the sake of answering your question, loop on model fields and use getattr to get the value:

def __str__(self):
    field_values = []
    for field in self._meta.get_all_field_names():
        field_values.append(getattr(self, field, ''))
    return ' '.join(field_values)

Upvotes: 4

Alasdair
Alasdair

Reputation: 308839

You can use the meta api to get a list of all the field names. Then you can loop through the fields and use getattr to get the value for each field.

Upvotes: 2

Related Questions