django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

fk_id is not understood, fk.id is

Open quertenmont opened this issue 3 years ago • 1 comments

Bug report

it seems that accessing foreign key field id with "foreignkey_id" is not understood. Accessing the field with "foreignkey.id" is properly understood but would trigger an extra SQL request, while "foreignkey_id" won't

class MyModel(models.Model):
    foreignkey = models.ForeignKey("whatever", on_delete=models.PROTECT, null=True)
    
    def __str__(self):
        return f"MyModel-fk={self.foreignkey_id}"

What's wrong

self.foreignkey_id raises

"Cannot access member "foreignkey_id" for type "MyModel"
  Member "foreignkey_id" is unknown

while self.foreignkey.id works fine but would trigger a SQL request to get self.foreignkey from DB while it's not needed here.

How is that should be

The _id (and/or _pk) syntax sould be understood for foreignKey and oneToOne

System information

  • OS: Ubuntu
  • python version: 3.10.4
  • django version: 4.0
  • mypy version: 0.971
  • django-stubs version: 1.12.0
  • django-stubs-ext version: 0.4.0

quertenmont avatar Aug 09 '22 13:08 quertenmont

I assume you have this happening because the mypy_django_plugin is not enabled. Take a look here at how to enable it.

monosans avatar Aug 11 '22 16:08 monosans

I'll close this with the resolution being what's mentioned in the above https://github.com/typeddjango/django-stubs/issues/1094#issuecomment-1212237485. This should work when the plugin is enabled.

Feel free to reopen or open a new issue if something isn't working.

flaeppe avatar Nov 01 '23 09:11 flaeppe