简体   繁体   中英

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:

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):

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. The WHERE clause says building.building_type=16. It looks right to me. I'm using Postgres. How do I make objects.filter() in Django evaluate an integer properly in PLPGSQL?

base_fields is a list of all the fields that were found when the metaclass executed. 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. 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 and fields are analogous to blueprints and actual buildings built. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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