Skip to content

Commit

Permalink
Merge f8a7c80 into 68ef4b5
Browse files Browse the repository at this point in the history
  • Loading branch information
atodorov committed Jan 22, 2018
2 parents 68ef4b5 + f8a7c80 commit e5065f3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
18 changes: 17 additions & 1 deletion pylint_django/transforms/foreignkey.py
@@ -1,4 +1,5 @@
from astroid import nodes, InferenceError, inference_tip, UseInferenceDefault
from astroid import MANAGER, nodes, InferenceError, inference_tip, UseInferenceDefault
from pylint_django.utils import node_is_subclass
from pylint_django.compat import ClassDef, instantiate_class, Attribute


Expand Down Expand Up @@ -33,6 +34,21 @@ def infer_key_classes(node, context=None):
else:
if key_cls is not None:
break
elif isinstance(arg, nodes.Const):
try:
model_name = arg.value.split('.')[-1] # can be 'Model' or 'app.Model'
except AttributeError:
break

for module in MANAGER.astroid_cache.values():
if model_name in module.locals:
class_defs = [
module_node for module_node in module.lookup(model_name)[1]
if isinstance(module_node, nodes.ClassDef)
and node_is_subclass(module_node, 'django.db.models.base.Model')
]
if class_defs:
return iter([instantiate_class(class_defs[0])()])
else:
raise UseInferenceDefault
return iter([instantiate_class(key_cls)()])
Expand Down
11 changes: 10 additions & 1 deletion test/input/func_noerror_foreignkeys.py
Expand Up @@ -17,7 +17,7 @@ class ISBN(models.Model):

class Book(models.Model):
book_name = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
author = models.ForeignKey('Author', on_delete=models.CASCADE)
isbn = models.OneToOneField(ISBN, on_delete=models.CASCADE)

def get_isbn(self):
Expand Down Expand Up @@ -47,3 +47,12 @@ class UserProfile(models.Model):

def get_username(self):
return self.user.username


class UserPreferences(models.Model):
"""
Used for testing FK which refers to another model by
string, not model class, see
https://github.com/landscapeio/pylint-django/issues/35
"""
user = ForeignKey('User', on_delete=models.CASCADE)

0 comments on commit e5065f3

Please sign in to comment.