python - .only django queryset 到底有什么作用?

标签 python django

我在 Django 文档中听说它进行了优化,所以我做了一些实验。所以我这样做了:

>>> x = Artist.objects.only('id').filter()
>>> print x.query
SELECT "store_artist"."id" FROM "store_artist"

>>> y = Artist.objects.filter()
>>> print y.query
SELECT "store_artist"."id", "store_artist"."name", "store_artist"."birth_date" FROM "store_artist"

我可以看到查询发生了变化,但是我做了进一步的测试:

>>> for _x in x:
    ... _x.name
    ... 
    u'Beyone'
    u'Beyoneeee'
    u'Beyone231231'
    u'Beyone2222'
    u'No Album'

>>> for _y in y: 
    ...  _y.name
    ...
    u'Beyone'
    u'Beyoneeee'
    u'Beyone231231'
    u'Beyone2222'
    u'No Album'

所以如果您注意到它有相同的结果。那是怎么发生的?我认为在 y 变量中我只是获取了 id,因此名称不应出现或无效

顺便说一句,这是我的模型:

class Artist(EsIndexable, models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()

最佳答案

它只查询您提供的字段,但仍然返回该模型的实例。因此,当您请求不同的字段时,您将进行第二次查询来获取名称

关于python - .only django queryset 到底有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405853/

相关文章:

python - 如何在循环期间更新 Django 查询集中的数据?

Python 3 奇怪的元类行为

Python:在 scipy.optimize.newton 中将列表作为参数传递

python - 使用 Django 时如何在命令行中退出 dbshel​​l (SQLite 3)?

django - django 中漂亮且 seo 友好的 url

python - Celery 为每个任务创建一个新连接

python - 如何按名称查找进程并使用 ctypes 终止进程?

django - 删除/清除 django.contrib.messages

python - 我真的需要在 Django 中使用 virtualenv 吗?

python - django-rosetta 翻译的短语没有出现在页面上