Skip to content

[DJ08] Model does not define __str__ method

Rocio Aramberri edited this page May 24, 2020 · 5 revisions

It is recommended to define an __str__ method within your models. The __str__ method is used whenever str(model_object) is called. Django calls str(model_object) in multiple places, one of those being the Django Admin, if you haven't set up your __str__ method the Django Admin will show something like: [object Object] as the value.

Don't

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150)

Do

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150)

    def __str__(self):
        return f'{self.title}'

References

https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.__str__