Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added testing translation stuff

  • Loading branch information...
commit 790fc1693744fe3a8f407080527a0c70b1f4a759 1 parent d16a5f4
Anssi Kääriäinen authored
19 django/core/management/validation.py
View
@@ -150,15 +150,16 @@ def get_validation_errors(outfile, app=None):
continue
# Make sure the related field specified by a ForeignKey is unique
- if len(f.foreign_related_fields) > 1:
- has_unique_field = False
- for rel_field in f.foreign_related_fields:
- has_unique_field = has_unique_field or rel_field.unique
- if not has_unique_field:
- e.add(opts, "Field combination '%s' under model '%s' must have a unique=True constraint" % (','.join([rel_field.name for rel_field in f.foreign_related_fields]), f.rel.to.__name__))
- else:
- if not f.foreign_related_fields[0].unique:
- e.add(opts, "Field '%s' under model '%s' must have a unique=True constraint." % (f.foreign_related_fields[0].name, f.rel.to.__name__))
+ if f.requires_unique_target:
+ if len(f.foreign_related_fields) > 1:
+ has_unique_field = False
+ for rel_field in f.foreign_related_fields:
+ has_unique_field = has_unique_field or rel_field.unique
+ if not has_unique_field:
+ e.add(opts, "Field combination '%s' under model '%s' must have a unique=True constraint" % (','.join([rel_field.name for rel_field in f.foreign_related_fields]), f.rel.to.__name__))
+ else:
+ if not f.foreign_related_fields[0].unique:
+ e.add(opts, "Field '%s' under model '%s' must have a unique=True constraint." % (f.foreign_related_fields[0].name, f.rel.to.__name__))
rel_opts = f.rel.to._meta
rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name()
6 django/db/models/fields/related.py
View
@@ -288,6 +288,7 @@ def __get__(self, instance, instance_type=None):
rel_obj = None
else:
params = {rh_field.attname: getattr(instance, lh_field.attname) for lh_field, rh_field in self.field.related_fields}
+ params.update(self.field.get_extra_filter())
qs = self.get_query_set(instance=instance)
# Assuming the database enforces foreign keys, this won't fail.
rel_obj = qs.get(**params)
@@ -897,6 +898,8 @@ def get_related_field(self):
class ForeignObject(RelatedField):
+ requires_unique_target = True
+
def __init__(self, to, from_fields, to_fields, **kwargs):
self.from_fields = from_fields
self.to_fields = to_fields
@@ -929,6 +932,9 @@ def resolve_related_fields(self):
return related_fields
+ def get_extra_filter(self):
+ return {}
+
@property
def related_fields(self):
if not hasattr(self, '_related_fields'):
38 tests/modeltests/foreign_object/models.py
View
@@ -1,6 +1,8 @@
import datetime
from django.db import models
+from django.utils.encoding import python_2_unicode_compatible
+from django.utils.translation import get_language
class Country(models.Model):
# Table Column Fields
@@ -85,3 +87,39 @@ class Friendship(models.Model):
from_fields=['to_friend_country_id', 'to_friend_id'],
to_fields=['person_country_id', 'id'],
related_name='to_friend')
+
+class ActiveTranslationField(models.ForeignObject):
+ requires_unique_target = False
+
+ def get_extra_join_sql(self, connection, qn, lhs_alias, rhs_alias):
+ return " AND %s.%s = %%s" % (qn(rhs_alias), qn("lang")), [get_language()]
+
+ def get_extra_filter(self):
+ return {'lang': get_language()}
+
+@python_2_unicode_compatible
+class Article(models.Model):
+ pub_date = models.DateTimeField()
+ active_translation = ActiveTranslationField(
+ 'ArticleTranslation',
+ from_fields=['id'],
+ to_fields=['article'],
+ related_name='+',
+ null=True)
+
+ def __str__(self):
+ try:
+ return self.active_translation.title
+ except ArticleTranslation.DoesNotExist:
+ return '[No translation found]'
+
+class ArticleTranslation(models.Model):
+ article = models.ForeignKey(Article)
+ lang = models.CharField(max_length='2')
+ title = models.CharField(max_length=100)
+ body = models.TextField()
+ abstract = models.CharField(max_length=400, null=True)
+
+ class Meta:
+ unique_together = ('article', 'lang')
+ ordering = ('active_translation__title',)
33 tests/modeltests/foreign_object/tests.py
View
@@ -1,8 +1,9 @@
import datetime
from operator import attrgetter
-from .models import Country, Person, Group, Membership, Friendship
+from .models import Country, Person, Group, Membership, Friendship, Article, ArticleTranslation
from django.test import TestCase
+from django.utils.translation import activate
class MultiColumnFKTests(TestCase):
def setUp(self):
@@ -262,3 +263,33 @@ def test_prefetch_related_m2m_reverse_works(self):
normal_groups_lists = [list(p.groups.all()) for p in Person.objects.all()]
self.assertEqual(groups_lists, normal_groups_lists)
+
+ def test_translations(self):
+ activate('fi')
+ a1 = Article.objects.create(pub_date=datetime.datetime.now())
+ at1_fi = ArticleTranslation(article=a1, lang='fi', title='Otsikko', body='Diipadaapa')
+ at1_fi.save()
+ at2_en = ArticleTranslation(article=a1, lang='en', title='Title', body='Lalalalala')
+ at2_en.save()
+ with self.assertNumQueries(1):
+ fetched = Article.objects.select_related('active_translation').get(active_translation__title='Otsikko')
+ self.assertTrue(fetched.active_translation.title == 'Otsikko')
+ a2 = Article.objects.create(pub_date=datetime.datetime.now())
+ at2_fi = ArticleTranslation(article=a2, lang='fi', title='Atsikko', body='Diipadaapa',
+ abstract='dipad')
+ at2_fi.save()
+ a3 = Article.objects.create(pub_date=datetime.datetime.now())
+ at3_en = ArticleTranslation(article=a3, lang='en', title='A title', body='lalalalala',
+ abstract='lala')
+ at3_en.save()
+ self.assertEqual(
+ list(Article.objects.filter(active_translation__abstract=None)),
+ [a1, a3])
+ self.assertEqual(
+ list(Article.objects.filter(active_translation__abstract=None,
+ active_translation__pk__isnull=False)),
+ [a1])
+ activate('en')
+ self.assertEqual(
+ list(Article.objects.filter(active_translation__abstract=None)),
+ [a1, a2])
Please sign in to comment.
Something went wrong with that request. Please try again.