Avoid does not exist error when creating model with user defined pk

This commit is contained in:
Oliver Sauder 2018-09-10 12:05:46 +02:00
parent 88e2d29596
commit b3b88d6d28
2 changed files with 12 additions and 2 deletions

View File

@ -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:

View File

@ -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."""