Attempt to rewrite related_names (ref #161).

This commit is contained in:
Jacek Tomaszewski 2013-03-08 21:13:37 +01:00
parent 16de24183a
commit fc798eaeb4
2 changed files with 11 additions and 4 deletions

View file

@ -51,8 +51,6 @@ def create_translation_field(model, field_name, lang):
if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS):
raise ImproperlyConfigured(
'%s is not supported by modeltranslation.' % cls_name)
if isinstance(field, fields.related.ForeignKey) and field.rel.related_name != '+':
raise ImproperlyConfigured('Translated ForeignKey fields must use related_name="+"')
translation_class = field_factory(field.__class__)
return translation_class(translated_field=field, language=lang)
@ -111,6 +109,13 @@ class TranslationField(object):
# (will show up e.g. in the admin).
self.verbose_name = build_localized_verbose_name(translated_field.verbose_name, language)
# ForeignKey support - rewrite related_name
if self.rel and self.related:
import copy
current = self.related.get_accessor_name()
self.rel = copy.copy(self.rel) # Since fields cannot share the same rel object.
self.rel.related_name = build_localized_fieldname(current, self.language)
# Django 1.5 changed definition of __hash__ for fields to be fine with hash requirements.
# It spoiled our machinery, since TranslationField has the same creation_counter as its
# original field and fields didn't get added to sets.

View file

@ -34,11 +34,13 @@ class FileFieldsModel(models.Model):
file = models.FileField(upload_to='modeltranslation_tests', null=True, blank=True)
image = models.ImageField(upload_to='modeltranslation_tests', null=True, blank=True)
########## Foreign Key fields testing
class ForeignKeyModel(models.Model):
test = models.ForeignKey(TestModel, null=True, related_name="+")
optional = models.ForeignKey(TestModel, blank=True, null=True, related_name="+")
test = models.ForeignKey(TestModel, null=True, related_name="test_fk")
optional = models.ForeignKey(TestModel, blank=True, null=True)
########## Custom fields testing