IndexError:当尝试打印模型对象

时间:2018-04-21 19:31:43

标签: python django models

这是我的模特:

class Book(models.Model):
    title = models.CharField(max_length=255)
    reviews = models.ManyToManyField(User, through="Review")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    def __repr__(self):
        return "<Book object: {}>".format(self.title)

在shell中,当我尝试使用Book.objects.all()进行打印时出现错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File 
 "/django/db/models/query.py", line 235, in __repr__
return '<QuerySet %r>' % data
File "/models.py", line 86, in __repr__
return "<Book object: {}>".format(self.title)
IndexError: tuple index out of range

1 个答案:

答案 0 :(得分:0)

def __repr__(self):
    """
    Just do this instead and move on with your life
    """
    return "<Book object: %s>" % (self.title)