我正在开发一个小型测试应用程序,目前无论我做什么查询,对象都只会返回模型中的第一个字段,而不是匹配的行数据?如果它打印查询,我会得到正确的 mysql 结果,所以不确定我在这里做错了什么?
型号:
class NotesPost(models.Model):
noteUrl = models.CharField(default='', max_length=16, blank=True, null=True)
notePostDate = models.CharField(default='', max_length=40)
noteName = models.CharField(max_length=255)
noteMessage = models.TextField()
def __str__(self):
return self.noteUrl
现在我在 shell 中执行以下操作
from testnotes.models import NotesPost
test = NotesPost.objects.filter(noteUrl='onjgRZBYTG')
但是我收到的是:
>>> test
<NotesPost: onjgRZBYTG>
>>> print(test.query)
我得到的结果(针对这篇文章进行排序)
SELECT
`notespost`.`id`,
`notespost`.`noteUrl`,
`notespost`.`notePostDate`,
`notespost`.`noteName`,
`notespost`.`noteMessage`
FROM
`notespost`
WHERE
`notespost`.`publicUrl` = 'onjgRZBYTG'
数据库中哪个是正确的并按预期返回整行? 因此,目前我不确定为什么我只接收查询对象的第一列而不是整行,因为我想更新该行并显示该行中的数据。
非常感谢
最佳答案
So at the moment i am unsure why i am only receiving the first column of the query object and not the whole row.
您不会只收到第一列。它只是打印第一列。为什么?因为您在 __str__
中指示了这一点实现:
class NotesPost(models.Model):
# …
def __str__(self):
return <b>self.noteUrl</b>
默认情况下,模型的 __repr__
实现返回 <ModelName: %s>
与 %s
str(object)
的结果打电话。
但这并不意味着对象本身仅包含特定数据。例如,您可以使用以下方式获取另一个属性:
test<b>[0].noteMessage</b>
这是您的 test
然而是QuerySet
的NotesPost
对象,因此是一个集合。您可以使用类似 .get(..)
[Django-doc] 的函数, .first(..)
[Django-doc] ,和 .last(..)
[Django-doc]获取模型对象。
关于python - Django mysql 查询仅返回第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60177052/