1👍
✅
Well book has null=True
, so self.book
, can be None
, and therefore self.book.title
does not per se makes sense.
In the __str__
you thus will first have to check if there is indeed a linked book
for that object, so:
class BookInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
book = models.ForeignKey(Book, on_delete=models.RESTRICT, null=True)
LOAN_STATUS = (
('m', 'Maintence'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(
max_length=1,
choices=LOAN_STATUS,
blank=True,
default='m',
help_text='Book Availability',
)
def __str__(self):
if self.book_id:
return f'{self.book.title} ({self.id})'
return str(self.id)
It is however a bit odd to make this null=True
, that thus means there can be BookInstance
s without a related Book
? It might be better to clean the database and thus look for BookInstance
s with book=None
, fix these, and mark the field as non-nullable.
Source:stackexchange.com