Skip to content

Commit

Permalink
Improved error when apps registry is not populated (#1204)
Browse files Browse the repository at this point in the history
  • Loading branch information
rpkilby committed Aug 26, 2021
1 parent 73484c2 commit 10bd30e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
16 changes: 12 additions & 4 deletions django_filters/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,18 @@ def get_field_parts(model, field_name):
return None

fields.append(field)
if isinstance(field, RelatedField):
opts = field.remote_field.model._meta
elif isinstance(field, ForeignObjectRel):
opts = field.related_model._meta
try:
if isinstance(field, RelatedField):
opts = field.remote_field.model._meta
elif isinstance(field, ForeignObjectRel):
opts = field.related_model._meta
except AttributeError:
# Lazy relationships are not resolved until registry is populated.
raise RuntimeError(
"Unable to resolve relationship `%s` for `%s`. Django is most "
"likely not initialized, and its apps registry not populated. "
"Ensure Django has finished setup before loading `FilterSet`s."
% (field_name, model._meta.label))

return fields

Expand Down
16 changes: 16 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,22 @@ def test_reverse_related_field(self):
self.assertIsInstance(parts[1], models.ManyToManyField)
self.assertIsInstance(parts[2], models.CharField)

def test_lazy_relationship_not_ready(self):
"""
This simulates trying to create a FilterSet before the app registry has
been populated. Lazy relationships have not yet been resolved from their
strings into their remote model referencess.
"""
class TestModel(models.Model):
fk = models.ForeignKey('remote.Model', on_delete=models.CASCADE)

msg = ("Unable to resolve relationship `fk__f` for `tests.TestModel`. "
"Django is most likely not initialized, and its apps registry "
"not populated. Ensure Django has finished setup before loading "
"`FilterSet`s.")
with self.assertRaisesMessage(RuntimeError, msg):
get_field_parts(TestModel, 'fk__f')


class GetModelFieldTests(TestCase):

Expand Down

0 comments on commit 10bd30e

Please sign in to comment.