引用 model.py 中的另一个字段 // Django

Reference to another field in model.py // Django

我想return在章节的str方法中,章节的标题和书的标题(来自书籍模型)。我需要它以便更好地显示在管理页面上。怎么做?

我应该在 Book 中创建一些新方法还是使用模型实例引用 https://docs.djangoproject.com/en/1.11/ref/models/instances/#model-instance-methods? 或者也许我应该使用带过滤器的检索特定 objects? 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: "+")"
def __str__(self):
    return '%s (%s)' % (self.title, self.book.title,)

要在管理面板中更好地打印对象数据,您应该覆盖模型的 __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)

`