Skip to content

Commit 7499c9d

Browse files
Tommy Wucarlio
Tommy Wu
authored andcommitted
Make the ForeiginKey detection more accurate
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
1 parent 8bab55e commit 7499c9d

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
Checks that Pylint doesn't raise an error when a 'ForeignKey' appears in a
3+
non-django class
4+
5+
The real case is described as follow:
6+
The project use tastypie and django.
7+
tastypie has a `ForeignKey` field which has the same name
8+
as django's `ForeignKey`.
9+
The issue is the lint trys resolving the `ForeignKey` for the
10+
tastypie `ForeignKey` which cause import error.
11+
"""
12+
from tastypie import fields
13+
from tastypie.fields import ForeignKey
14+
15+
# pylint: disable=missing-docstring
16+
from tastypie.resources import ModelResource
17+
18+
19+
class MyTestResource(ModelResource): # pylint: disable=too-few-public-methods
20+
field1 = ForeignKey("myapp.api.resource", "xxx")
21+
field2 = fields.ForeignKey("myapp.api.resource", "xxx")

Diff for: pylint_django/transforms/foreignkey.py

+5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ def is_foreignkey_in_class(node):
1313
if not isinstance(node.parent.parent, ClassDef):
1414
return False
1515

16+
# Make sure the outfit class is the subclass of django.db.models.Model
17+
is_in_django_model_class = node_is_subclass(node.parent.parent, "django.db.models.base.Model", ".Model")
18+
if not is_in_django_model_class:
19+
return False
20+
1621
if isinstance(node.func, Attribute):
1722
attr = node.func.attrname
1823
elif isinstance(node.func, nodes.Name):

Diff for: setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
],
2424
extras_require={
2525
"with_django": ["Django"],
26-
"for_tests": ["django_tables2", "factory-boy", "coverage", "pytest", "wheel"],
26+
"for_tests": ["django_tables2", "factory-boy", "coverage", "pytest", "wheel", "django-tastypie"],
2727
},
2828
license="GPLv2",
2929
classifiers=[

0 commit comments

Comments
 (0)