diff --git a/localized_fields/descriptor.py b/localized_fields/descriptor.py index dd7000a..4d2babc 100644 --- a/localized_fields/descriptor.py +++ b/localized_fields/descriptor.py @@ -41,7 +41,7 @@ class LocalizedValueDescriptor: if self.field.name in instance.__dict__: value = instance.__dict__[self.field.name] - elif instance.pk is not None: + elif not instance._state.adding: instance.refresh_from_db(fields=[self.field.name]) value = getattr(instance, self.field.name) else: diff --git a/tests/test_field.py b/tests/test_field.py index 3bd896c..de60523 100644 --- a/tests/test_field.py +++ b/tests/test_field.py @@ -1,6 +1,7 @@ import json from django.conf import settings +from django.db import models from django.db.utils import IntegrityError from django.test import TestCase @@ -33,7 +34,6 @@ class LocalizedFieldTestCase(TestCase): field = LocalizedField(required=False) assert field.required == [] - @staticmethod def test_from_db_value(): """Tests whether the :see:from_db_value function @@ -205,6 +205,16 @@ class LocalizedFieldTestCase(TestCase): for field in field.formfield().fields: assert field.required + def test_descriptor_user_defined_primary_key(self): + """Tests that descriptor works even when primary key is user defined.""" + model = get_fake_model(dict( + slug=models.SlugField(primary_key=True), + title=LocalizedField() + )) + + obj = model.objects.create(slug='test', title='test') + assert obj.title == 'test' + def test_required_all(self): """Tests whether passing required=True properly validates that all languages are filled in."""