Skip to content

kwargs to the queryset "filter()" method not type checked in chained filter operations #1172

@Pastromhaug

Description

@Pastromhaug

Bug report

What's wrong

Kwargs passed into the .filter() method on a queryset only have type checking the first time filter is called on the queryset. All subsequent calls to filter on the same queryset do not have their arguments checked.

Here's an example file:

from django.db import models

class Cheese(models.Model):
    a = models.BooleanField()
    
def f() -> None:
    Cheese.objects.filter(field=True).filter(field2=True)
    qs = Cheese.objects.all()
    qs.filter(field=True)

Running mypy outputs the following:

app/models.py:7: error: Cannot resolve keyword 'field' into field. Choices are: a, id  [misc]
Found 1 error in 1 file (checked 13 source files)

There is only 1 error caught by mypy here, but there should really be 3! The code above calls filter 3 times, each time with arguments that should fail type checking.

I also tried the following other solutions, but only django-stubs 1.8.0 worked:

  • upgrading django to 4.1.1
  • upgrading and downgrading mypy
  • django-stubs 1.9.0, 1.10.0, 1.11.0, 1.12.0
  • pinning the latest master commit of django-stubs

How it should be

Mypy should output 3 errors for the code sample above. Rerunning mypy with django-stubs 1.8.0 catches all 3 errors:

app/models.py:7: error: Cannot resolve keyword 'field' into field. Choices are: a, id  [misc]
app/models.py:7: error: Cannot resolve keyword 'field2' into field. Choices are: a, id  [misc]
app/models.py:9: error: Cannot resolve keyword 'field' into field. Choices are: a, id  [misc]
Found 3 errors in 1 file (checked 13 source files)

System information

  • OS: MacOS Big Sur 11.7
  • python version: 3.8.9
  • django version: 4.1.1
  • mypy version: 0.981
  • django-stubs version: 1.12.0
  • django-stubs-ext version: 0.5.0

Here is a minimum repo for reproducing this issue: https://github.com/Pastromhaug/django-stubs-filter-bug
At my company we have temporarily pinned django-stubs to 1.8.0 to work around this.

Hope this is helpful! Happy to answer any questions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingmypy-pluginIssues specific to mypy_django_plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions