str and the Meta Class
Make objects readable and set table behavior.
Make Objects Readable
Out of the box, a model object prints as a vague Object 1. You can fix that and also shape table behavior cleanly.
Define __str__
Add a __str__ method to return a friendly label. Now your object shows its title instead of a useless number.
class Book(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.titleAll lessons in this course
- Defining a Model Class
- Choosing Field Types
- Field Options: null, blank, default
- str and the Meta Class