user_5
user_5

Reputation: 576

Django/Parler: unable to access the translated fields of a model in the update_or_create function

I have a model such as below:

class MyModel(TranslatableModel):
    date_created = models.DateField(
        verbose_name=_('Date Created'), default=timezone.now)
    source = models.CharField(max_length=100, verbose_name=('Type'))
    translations = TranslatedFields(
        name=models.CharField(verbose_name=_('Name'), max_length=200)
    )

I want to use update_or_create function on this model; I want to fetch a record which has the given id and source; If it exists I want to update its name in 3 different languages. Otherwise I want to create a new record. I used the following code. I tried name_en, name__en, translations__name_en; None of them worked. I also tried get_or_create function, None of them worked with that as well.

obj, created = MyModel.objects.update_or_create(
                                            id= id,
                                            source = 'tmp',
                                            defaults={
                                                    'name_en': en_name,
                                                    'name_fi': fi_name,
                                                    'name_sv': sv_name,
                                             })

I don't want to use get function and create function separately. I would like to know how to access the django translated fields via update_or_create function or get_or_create function. Can some one help me with this please?

My Django version: Django==1.11.17

Upvotes: -1

Views: 1306

Answers (1)

iklinac
iklinac

Reputation: 15748

update_or_create creates object/updates object fields and it is not built to create related models/update fields on related model

This is meant as a shortcut to boilerplatish code. For example:

defaults = {'first_name': 'Bob'}
try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
    for key, value in defaults.items():
        setattr(obj, key, value)
    obj.save()
except Person.DoesNotExist:
    new_values = {'first_name': 'John', 'last_name': 'Lennon'}
    new_values.update(defaults)
    obj = Person(**new_values)
    obj.save()

And as documented

Internally, django-parler stores the translated fields in a separate model, with one row per language.

Also same is visible from source

Upvotes: 1

Related Questions