2

我有一个简单的应用程序:

class NamedModel(TranslatableModel):
    code = models.CharField(max_length=120)

    translations = TranslatedFields(
        name=models.CharField(max_length=256),
        description=models.TextField()
    )

    class Meta:
        abstract = True


class Product(NamedModel):
    translations = TranslatedFields()


class Report(TranslatableModel):
    quantity = models.DecimalField(max_digits=20, decimal_places=6)
    inv = models.ForeignKey(Inv)
    translations = TranslatedFields(
        product=models.ForeignKey(Product)
    )

然后,从 shell 我创建了一些实例:

product = Product.objects.language('en').create(name='asd', description='asd', code='asd')

inv = Inv.objects.create(code='xxx')

report = Report.objects.language('en').create(quantity=1, inv=inv, product=product)

如果我输入:len(Report.objects.language('en').all()),我得到 1,但是当我尝试这个时:

Report.objects.language('en').all()

我得到:

NoTranslationError: Accessing a translated field requires that the instance has a translation loaded, or a valid translation in current language (None) loadable from the database

你有什么建议吗?

4

1 回答 1

0

您需要为当前会话明确设置活动语言。请参阅 Django 文档“显式设置活动语言”

from django.utils import translation

user_language = 'en'
translation.activate(user_language)
于 2017-09-15T13:30:53.953 回答