python - Django mysql 查询仅返回第一列

标签 python django

我正在开发一个小型测试应用程序,目前无论我做什么查询,对象都只会返回模型中的第一个字段,而不是匹配的行数据?如果它打印查询,我会得到正确的 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然而是QuerySetNotesPost对象,因此是一个集合。您可以使用类似 .get(..) [Django-doc] 的函数, .first(..) [Django-doc] ,和 .last(..) [Django-doc]获取模型对象

关于python - Django mysql 查询仅返回第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60177052/

相关文章:

python - 当折线图不从第一个 x 轴刻度开始时,如何使 x 轴刻度之间的间距保持一致

Python 多处理在绘图期间挂起

python - 响应无法使用 Selenium 滚动更新

django - 在 Django 中使用 {% url %} 时的 NoReverseMatch

python - Django 1.11 上下文处理器错误 : TypeError: context must be a dict rather than RequestContext'

django - Django TemplateView 的 xframe_options_exempt

python - 如何使用 Beautiful Soup(模态容器)抓取 HTML 数据端点

python - 如何在 python 控制台中运行 Odoo ORM 方法?

django - 通过 nginx 为临时和生产站点提供服务?

python - 不要在 Django CMS 的导航菜单中显示主页