运行基本django查询时,为什么我得到int()异常错误的无效文字?

时间:2017-01-10 00:00:47

标签: django models

一个简单的django查询无效,我想知道为什么

models.py

class Entry(models.Model):
    headline= models.CharField(max_length=200,)
    body_text = models.TextField()
    author=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='entryauthors')
    pub_date=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return u'%s %s %s %s %s %s %s' % (self.headline, self.body_text, self.author, self.pub_date)

在django shell或我的观点中,我尝试了

itemstosell = Entry.objects.get(author=username)[:4]

导致:

Exception Type: ValueError
Exception Value: invalid literal for int() with base 10: 'john'

2 个答案:

答案 0 :(得分:0)

因为author是外键,因此将引用用户模型上可能是整数的主键。你应该做的

read()

答案 1 :(得分:0)

默认情况下," get"方法只返回1个结果。我们这样使用它: itemstosell = Entry.objects.get(pk = 1)

"过滤器"方法可以返回QuerySet,如果你想使用"(author__username = username)[:4]"作为一个选项,你应该使用这种风格: itemstosell = Entry.objects.filter(author__username = username)[:4]