Commits

Branko Vukelic committed 062a75f

Fixed #1: Restrict uniqueness of unique source fields to language

  • Participants
  • Parent commits 65b11cb

Comments (0)

Files changed (3)

File i18n_model/models.py

                 ]
             ]
 
+        unique_fields = []
+
         # We have the field names we need to copy, so let's copy them over
         # into our new model.
         for field in source._meta.fields:
             if field.name in fields:
                 attrs[field.name] = copy.deepcopy(field)
 
+                if field._unique:
+                    # We don't allow unique fields in translations.
+                    attrs[field.name]._unique = False
+                    unique_fields.append(field.name)
+
         # Add unique_together to Meta
         if hasattr(attr_meta, 'unique_together'):
             if type(attrs['Meta'].unique_together[0]) in (str, unicode):
                     'i18n_language'
                 )
         else:
-            attrs['Meta'].unique_together = ('i18n_source', 'i18n_language')
+            attrs['Meta'].unique_together = (('i18n_source', 'i18n_language'),)
+
+        # Also include unique fields in unique_together if needed
+        if unique_fields:
+            for field in unique_fields:
+                attrs['Meta'].unique_together += (('i18n_language', field),)
 
         # Let's also add a reference to the original model
         attrs['i18n_source'] = models.ForeignKey(

File tests/models.py

 class NewsTranslation(I18nModel):
     class Meta:
         source_model = 'tests.News'
+
+
+class ModelWithUniqueField(models.Model):
+    slug = models.SlugField(unique=True)
+
+
+class ModelWithUniqueFieldI18N(I18nModel):
+    class Meta:
+        translation_fields = ('slug')

File tests/test_unique_field.py

+""" Tests for unique field handling
+"""
+
+from django.conf import settings
+from django.db import models
+
+from .models import ModelWithUniqueField, ModelWithUniqueFieldI18N
+from .model_test_case import ModelTestCase
+
+
+class UniqueFieldTestCase(ModelTestCase):
+    """
+    Tests ensure that unique fields are unique per langauge
+    """
+
+    def test_unique_field(self):
+        """
+        Unique field in translation model should no longer be unique
+        """
+        self.assertHasField(ModelWithUniqueFieldI18N, 'slug')
+        self.assertFalse(ModelWithUniqueFieldI18N._meta.fields[2]._unique)
+
+    def test_unique_together(self):
+        """
+        Unique fields from original model should now be unique_together
+        """
+        self.assertTrue(('i18n_language', 'slug') in
+                        ModelWithUniqueFieldI18N._meta.unique_together)
+