Reputation: 522
I am writing a django app. I'm curious if there is a better way of writing the python "magic method" __str__()
that returns a string representation of any object. Currently, following the Django docs I find that you can do the following...
class Todo(models.Model):
firstName = models.CharField(max_length=30)
secondName = models.CharField(max_length=30)
def __str__(self):
"%s %s" % (self.firstName, self.secondName)
Fine and dandy but if I have 8, or even more fields, then it gets kind of annoying to do this. First I find myself counting how many fields I want and make sure to write out %s
that many times just to then write out self.
the same amount of times and this really sucks.
I was hoping to if anyone knows of easier ways of writing this out and if there are what are the differences. I haven't been able to find another method online so I'd appreciate some help.
Upvotes: 0
Views: 4286
Reputation: 933
If you are using Python >=3.6, then you can use f-strings.
def __str__(self):
return f"{self.firstName} {self.secondName}"
Upvotes: 1