B
B
beginer02020-04-21 17:24:10
Django
beginer0, 2020-04-21 17:24:10

How to return as a list in the __str__ function of a model in Django?

There is a Test model with fields "name, first_name, last_name", I know that there is a function "def __str__(self):
return self.name " which in the shell returns the value of the field "name". how to make it return a list with the values ​​of all fields of the Test model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-21
@beginer0

Using __str__ to return a list is a bad idea, but a string with a serialized list - why not?
I usually do something like this:

def __repr__(self):
    return f'{type(self).__name__}({self.name!r}, {self.first_name!r}, {self.last_name!r})'

If __str__ is not declared separately, then __repr__ will be called when str(obj) is called.
You can also use it as a list if you want:
def __str__(self):
    return f'{[self.name, self.first_name, self.last_name]!r}'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question