简体   繁体   English

关于整数问题的 Django 模型外键过滤

[英]Django model foreign key filtering on integer issue

I have a Building model with an integer field indicating the type of building:我有一个带有整数字段的建筑模型,指示建筑物的类型:

class Building(models.Model):
    building_type = models.PositiveIntegerField('Building Type')

I have a BuildingUnit model with a foreign key reference to Building:我有一个 BuildingUnit 模型,其中包含对 Building 的外键引用:

class BuildingUnit(models.Model):
    building_fk = models.ForeignKey(
        'Building',
        on_delete=models.CASCADE, verbose_name="Building"
    )

I am overriding the BuildingUnit model's init function and attempting to filter the foreign keys based on an integer value (the type of building it is):我正在覆盖 BuildingUnit 模型的init函数并尝试根据整数值(建筑物的类型)过滤外键:

self.base_fields['building_fk'].queryset = BuildingUnit.objects.filter
(building_fk__building_type=16)

It does not work.这是行不通的。 All building types continue to come back.所有建筑类型都在继续回归。 When I debug and inspect the SQL statement, it says invalid syntax.当我调试和检查 SQL 语句时,它说语法无效。 The WHERE clause says building.building_type=16. WHERE 子句表示 building.building_type=16。 It looks right to me.在我看来是正确的。 I'm using Postgres.我正在使用 Postgres。 How do I make objects.filter() in Django evaluate an integer properly in PLPGSQL?如何使 Django 中的 objects.filter() 在 PLPGSQL 中正确评估整数?

base_fields is a list of all the fields that were found when the metaclass executed. base_fields是元类执行时找到的所有字段的列表。 These are those fields that were actually declared directly on the class, like an original/global/main definition.这些是实际直接在类上声明的字段,如原始/全局/主定义。

fields are those that will actually be used to generate HTML for the form, as well as validate user input.字段是那些实际用于为表单生成 HTML 以及验证用户输入的字段 It begins as a copy of base_fields , and fields may be used when doing customisation of the form, such as adding new fields dynamically to the form, or changing values/choices of existing fields.它以base_fields的副本开始,在自定义表单时可能会使用字段,例如向表单动态添加新字段,或更改现有字段的值/选择。

base_fields and fields are analogous to blueprints and actual buildings built. base_fieldsfields类似于蓝图和实际建造的建筑物。 The blueprint is the main definition.蓝图是主要的定义。 Once you make a change there, the change is global and persistent in scope.一旦您在那里进行更改,该更改将是全局且持久的。 fields is like the house you build.田野就像你建造的房子。 You can make any number of the same kind of house out of the original spec.您可以根据原始规格制作任意数量的相同类型的房屋。 However, you can make customisations on each individual house to make each one unique and special.但是,您可以对每栋房屋进行定制,使每栋房屋都独一无二。

It wasn't working for me because I wasn't assigning the filtered values to the field attribute that was generating the actual HTML output.它对我不起作用,因为我没有将过滤后的值分配给生成实际 HTML 输出的字段属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM