在模型中的f字符串内插行上获取语法错误
使用python3.6设置venv,因此不确定为什么会这样。
从django.db导入模型
类流派(models.Model): “”“代表书籍类型的模型。”“” name = models.CharField(max_length = 200,help_text ='输入图书类型(例如科幻小说)')
def __str__(self):
"""String for representing the Model object."""
return self.name
from django.urls import reverse#用于通过反转URL模式生成URL
Class Book(models.Model): “”“代表书籍的模型(但不是书籍的特定副本)。”“” title = models.CharField(max_length = 200)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
# ManyToManyField used because genre can contain many books. Books can cover many genres.
# Genre class has already been defined so we can specify the object above.
genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
def __str__(self):
"""String for representing the Model object."""
return self.title
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('book-detail', args=[str(self.id)])
import uuid#唯一书本实例必需
Class BookInstance(models.Model): “”“代表书籍特定副本的模型(即可以从图书馆借来的模型)。”“”“ id = models.UUIDField(primary_key = True,默认值= uuid.uuid4,help_text ='该特定书籍在整个图书馆中的唯一ID') book = models.ForeignKey('Book',on_delete = models.SET_NULL,null = True) 版本说明= models.CharField(max_length = 200) due_back = models.DateField(null = True,空白= True)
LOAN_STATUS = (
('m', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(
max_length=1,
choices=LOAN_STATUS,
blank=True,
default='m',
help_text='Book availability',
)
class Meta:
ordering = ['due_back']
def __str__(self):
"""String for representing the Model object."""
return f'{self.id} ({self.book.title})'
类作者(models.Model): “”“代表作者的模型。”“” first_name = models.CharField(最大长度= 100) last_name = models.CharField(最大长度= 100) date_of_birth = models.DateField(null = True,blank = True) date_of_death = models.DateField('Died',null = True,blank = True)
class Meta:
ordering = ['last_name', 'first_name']
def get_absolute_url(self):
"""Returns the url to access a particular author instance."""
return reverse('author-detail', args=[str(self.id)])
def __str__(self):
"""String for representing the Model object."""
return f'{self.last_name}, {self.first_name}'
答案 0 :(得分:0)
您可以通过以下操作解决此问题:
Class BookInstance
def __str__(self):
"""String for representing the Model object."""
return '{0} ({1})'.format(self.id, self.book.title)
班级作者
def __str__(self):
"""String for representing the Model object."""
return '{0}, {1}'.format{self.last_name, self.first_name)
您可以在documentation
中获取有关格式的更多信息