Return default value None if attribute choices doesn't exist

Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
This commit is contained in:
Viktor 2022-06-24 16:27:50 +02:00 committed by Hasan Ramezani
parent 11dceb81b8
commit d928ff7f77
3 changed files with 12 additions and 4 deletions

View file

@ -353,7 +353,7 @@ class LogEntry(models.Model):
values_display = []
# handle choices fields and Postgres ArrayField to get human readable version
choices_dict = None
if getattr(field, "choices") and len(field.choices) > 0:
if getattr(field, "choices", None) and len(field.choices) > 0:
choices_dict = dict(field.choices)
if (
hasattr(field, "base_field")

View file

@ -73,7 +73,9 @@ class RelatedModel(RelatedModelParent):
A model with a foreign key.
"""
related = models.ForeignKey(to="SimpleModel", on_delete=models.CASCADE)
related = models.ForeignKey(
"SimpleModel", related_name="related_models", on_delete=models.CASCADE
)
one_to_one = models.OneToOneField(
to="SimpleModel", on_delete=models.CASCADE, related_name="reverse_one_to_one"
)

View file

@ -1131,6 +1131,12 @@ class ChoicesFieldModelTest(TestCase):
msg="The human readable text 'Red' is displayed.",
)
def test_changes_display_dict_many_to_one_relation(self):
obj = SimpleModel()
obj.save()
history = obj.history.get()
assert "related_models" in history.changes_display_dict
class CharfieldTextfieldModelTest(TestCase):
def setUp(self):
@ -1446,11 +1452,11 @@ class ModelInstanceDiffTest(TestCase):
simple1.reverse_one_to_one # equals None
# accessing relatedmodel_set won't trigger DoesNotExist.
self.assertEqual(simple1.relatedmodel_set.count(), 0)
self.assertEqual(simple1.related_models.count(), 0)
# simple2 DOES have these relations
self.assertEqual(simple2.reverse_one_to_one, related)
self.assertEqual(simple2.relatedmodel_set.count(), 1)
self.assertEqual(simple2.related_models.count(), 1)
model_instance_diff(simple2, simple1)
model_instance_diff(simple1, simple2)