Skip to content

Commit

Permalink
Fixes pylint-dev#208 Support recursive (self) ForeignKey relations
Browse files Browse the repository at this point in the history
  • Loading branch information
fadedDexofan committed Apr 17, 2019
1 parent 443415f commit 86ac419
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
11 changes: 11 additions & 0 deletions pylint_django/tests/input/func_noerror_foreignkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ def get_username(self):
return self.user.username


class Human(models.Model):
child = ForeignKey('self', on_delete=models.SET_NULL, null=True)
parent = ForeignKey(to='self', on_delete=models.SET_NULL, null=True)

def get_grandchild(self):
return self.child.child

def get_grandparent(self):
return self.parent.parent


class UserPreferences(models.Model):
"""
Used for testing FK which refers to another model by
Expand Down
21 changes: 18 additions & 3 deletions pylint_django/transforms/foreignkey.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from itertools import chain

from astroid import MANAGER, nodes, InferenceError, inference_tip, UseInferenceDefault
from astroid import (
MANAGER, nodes, InferenceError, inference_tip,
UseInferenceDefault
)
from astroid.nodes import ClassDef, Attribute

from pylint_django.utils import node_is_subclass
Expand Down Expand Up @@ -42,8 +45,20 @@ def infer_key_classes(node, context=None):
break
elif isinstance(arg, nodes.Const):
try:
# can be 'Model' or 'app.Model'
module_name, _, model_name = arg.value.rpartition('.')
# can be 'self , 'Model' or 'app.Model'
if arg.value == 'self':
module_name = ''
# for relations with `to` first parent be Keyword(arg='to')
# and we need to go deeper in parent tree to get model name
if (
isinstance(arg.parent, nodes.Keyword)
and arg.parent.arg == 'to'
):
model_name = arg.parent.parent.parent.parent.name
else:
model_name = arg.parent.parent.parent.name
else:
module_name, _, model_name = arg.value.rpartition('.')
except AttributeError:
break

Expand Down

0 comments on commit 86ac419

Please sign in to comment.