Skip to content

Commit

Permalink
Make the ForeiginKey detection more accurate
Browse files Browse the repository at this point in the history
To handle this case: the project use tastypie and django.
tastypie has a `ForeignKey` field which has the same name
as django's `ForeignKey`.
The issue is the lint trys resolving the `ForeignKey` for the
tastypie `ForeignKey` which cause import error.

In this commit, add a check to ensure the current class of the
`ForeignKey` is a subclass of `Model` of django.

Tested manually
Test case added: func_noerror_foreign_key_in_non_django_class
  • Loading branch information
Tommy Wu committed Sep 7, 2021
1 parent f4f609e commit b5edc63
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
Checks that Pylint raise error when a 'ForeignKey' appears in a
non-django class
The real case is described as follow:
The project use tastypie and django.
tastypie has a `ForeignKey` field which has the same name
as django's `ForeignKey`.
The issue is the lint trys resolving the `ForeignKey` for the
tastypie `ForeignKey` which cause import error.
"""
# pylint: disable=missing-docstring

class ForeignKey: # pylint: disable=too-few-public-methods
def test_methond(self):
pass


class Resource: # pylint: disable=too-few-public-methods
def test_methond(self):
pass


class MyTestResource(Resource): # pylint: disable=too-few-public-methods
author = ForeignKey('myapp.api.resource', 'xxx')
5 changes: 5 additions & 0 deletions pylint_django/transforms/foreignkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def is_foreignkey_in_class(node):
if not isinstance(node.parent.parent, ClassDef):
return False

# Make sure the outfit class is the subclass of django.db.models.Model
is_in_django_model_class = node_is_subclass(node.parent.parent, 'Model')
if not is_in_django_model_class:
return False

if isinstance(node.func, Attribute):
attr = node.func.attrname
elif isinstance(node.func, nodes.Name):
Expand Down

0 comments on commit b5edc63

Please sign in to comment.