Skip to content

Commit b5edc63

Browse files
author
Tommy Wu
committed
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 f4f609e commit b5edc63

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
Checks that Pylint raise 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+
# pylint: disable=missing-docstring
13+
14+
class ForeignKey: # pylint: disable=too-few-public-methods
15+
def test_methond(self):
16+
pass
17+
18+
19+
class Resource: # pylint: disable=too-few-public-methods
20+
def test_methond(self):
21+
pass
22+
23+
24+
class MyTestResource(Resource): # pylint: disable=too-few-public-methods
25+
author = ForeignKey('myapp.api.resource', 'xxx')

pylint_django/transforms/foreignkey.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ def is_foreignkey_in_class(node):
1616
if not isinstance(node.parent.parent, ClassDef):
1717
return False
1818

19+
# Make sure the outfit class is the subclass of django.db.models.Model
20+
is_in_django_model_class = node_is_subclass(node.parent.parent, 'Model')
21+
if not is_in_django_model_class:
22+
return False
23+
1924
if isinstance(node.func, Attribute):
2025
attr = node.func.attrname
2126
elif isinstance(node.func, nodes.Name):

0 commit comments

Comments
 (0)