python - Django F 字段迭代

标签 python django

我创建了一个简单的 Django 模型来探索 F 字段,但可以迭代该字段。

class PostgreSQLModel(models.Model):
    class Meta:
        abstract = True
        required_db_vendor = 'postgresql'

class NullableIntegerArrayModel(PostgreSQLModel):
    field = ArrayField(models.IntegerField(), blank=True, null=True)    

现在,我从我的 django shell 创建了一个 F 对象,如下所示。不确定该对象包含什么。它包含所有的 id 吗?如何迭代结果?

>>> a=F('id')
>>> a
F(id)
>>> dir(a)
['ADD', 'BITAND', 'BITOR', 'DIV', 'MOD', 'MUL', 'POW', 'SUB', '__add__', '__and__', '__class__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__or__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_combine', 'asc', 'bitand', 'bitor', 'desc', 'name', 'resolve_expression']

最佳答案

F 不是字段。

An F() object represents the value of a model field or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory. - F() expressions

总之,只要您需要在查询中引用另一个字段的值,就可以使用 F() 对象。就其本身而言,F() 对象没有任何意义。它们用于引用同一查询集上的字段值。

例如(一个非常简单的示例),在您的模型中,如果您想查询 field 值是其 id 两倍的对象,则需要 reference id field's value,而过滤,因此您可以像这样使用 F():

NullableIntegerArrayModel.objects.filter(field=F('id') *2)

F('id') 仅引用该模型的 id 值。 Django 使用它来创建相应的 SQL 语句。在这种情况下是这样的:

'SELECT "app_model"."id", "app_model"."field" FROM "app_model" 
 WHERE "app_model"."field" = (("app_model"."id" * 2))'

如果没有 F() 表达式,您将编写原始 SQL 或在 Python 中进行过滤(这会降低性能,尤其是在存在大量对象时)。

<小时/>

引用文献:

来自F()类定义:

An object capable of resolving references to existing query objects. - F source

关于python - Django F 字段迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402920/

相关文章:

python - 如何获取 PyQt 中 QGroupbox 中存在的 Qcheckbox 的状态

python - Django 查询集 : Need help in optimizing this set of queries

Django从模态窗口登录

python - 从 Django 下载的 docx 文件已损坏

python - Django 1.6 : How to pass value from a dropdown to another template page

python - 如何以编程方式创建具有动画方面的图片

python - unicodedata.normalize(form, unistr) 是如何工作的?

python - YAML 格式不正确

python - 自动设置 matplotlib 范围的 Y 限制

python - 用户注册错误 : no such table: auth_user