我想返回章节的 str 方法,章节的标题和书的标题(来自书籍模型)。我需要它以便在管理页面上更好地显示。怎么做?
我应该在Book中创建一些新方法还是使用Model实例引用https://docs.djangoproject.com/en/1.11/ref/models/instances/#model-instance-methods? 或者我应该使用过滤器检索特定对象? https://docs.djangoproject.com/en/1.11/topics/db/queries/#retrieving-objects
我是django的新手,请提前感谢您的解决方案。
class Book(models.Model):
author = models.CharField(max_length=200)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
def __str__(self):
return self.title+" ("+self.author+")"
def book_author(self):
return self.author
class Chapter(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
body = models.TextField()
hierarchy = models.IntegerField()
sort = models.IntegerField(unique=True)
def __str__(self):
print(repr(Book))
print(repr(Book.author))
# print(repr(Book.objects.all().filter(id==1)))
# print(repr(Book.objects.get(id=1)))
print(repr(Book.book_author(self)))
return self.title+"(book: "+")"
答案 0 :(得分:1)
def __str__(self):
return '%s (%s)' % (self.title, self.book.title,)
答案 1 :(得分:0)
要更好地在管理面板中打印对象数据,您应该为模型覆盖__str__
方法。
例如,您的代码应如下所示:
class Book(models.Model):
author = models.CharField(max_length=200)
title = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
def __str__(self):
return 'Book with title: {} writen by {}'.format(self.title, self.author)
`