Home > Mobile >  the problem is still return object not title and how to add in reference models
the problem is still return object not title and how to add in reference models

Time:02-17

class Interest(models.Model): title = models.CharField(max_length=200)

def _str_(self):
    return self.title

I have trying use str to return the title but unfortunately it return back object 1

CodePudding user response:

You need to user double underscore (__)

so it'll look like:

def __str__(self):
    return self.title

CodePudding user response:

conventions

__bar__: a way for the Python system to use names that won't conflict with user names.

_bar: a way for the programmer to indicate that the variable is private (whatever that means in Python).

__bar: this has real meaning: the interpreter replaces this name with _classname__bar as a way to ensure that the name will not overlap with a similar name in another class.

No other form of underscores have meaning in the Python world, so you should use __str__ nor _str_

class Interest(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

Other examples:

__init__(), __call__(), __add__(), __new__ ...

  • Related