# Model Translations

**URL:** <https://forum.djangoproject.com/t/model-translations/25323>\
**Category:** Using the ORM\
**Created:** [November 14, 2023, 12:32pm UTC](https://forum.djangoproject.com/t/model-translations/25323 "2023-11-14T12:32:30Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![dauid64](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dauid64/32/17084_2.png) [@dauid64](https://forum.djangoproject.com/u/dauid64)\
**Post date:** [November 14, 2023, 12:32pm UTC](https://forum.djangoproject.com/t/model-translations/25323/1 "2023-11-14T12:32:30Z")

</div>

Hi  
My app have these two models.  
Templates

```auto
class Templates(models.Model):
    id = models.BigAutoField(primary_key=True)
    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)
    image_url = models.TextField(blank=True, null=True)
    type = models.TextField()
    model = models.TextField(blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    max_tokens = models.BigIntegerField(blank=True, null=True)
    top_p = models.FloatField(blank=True, null=True)
    frequency_penalty = models.FloatField(blank=True, null=True)
    presence_penalty = models.FloatField(blank=True, null=True)
    has_voice_tone = models.BooleanField(blank=True, null=True)
    has_examples = models.BooleanField(blank=True, null=True)
    has_keywords = models.BooleanField(blank=True, null=True)
    categories = models.ManyToManyField(
        'Categories', through="TemplateCategories", blank=True)

    class Meta:
        managed = False
        db_table = 'templates'

```

TemplateTranslations

```auto
class TemplateTranslations(models.Model):
    id = models.BigAutoField(primary_key=True)
    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)
    template = models.ForeignKey('Templates', models.DO_NOTHING)
    language = models.ForeignKey(Languages, models.DO_NOTHING)
    name = models.TextField()
    description = models.TextField()
    video_url = models.TextField()

    def __str__ (self):
        return self.name

    class Meta:
        managed = False
        db_table = 'template_translations'

```

I want get name for the each template at language=1, but when i set **str** the ORM django does much queries

example

```auto
def __str__ (self):
        translation = self.templatetranslations_set.filter(language=1).first()
        return translation.name if translation else str(self.id)
``
```

---

<div class="post-metadata">

**Author:** ![shangxiao](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/shangxiao/32/10313_2.png) [@shangxiao](https://forum.djangoproject.com/u/shangxiao)\
**Post date:** [November 14, 2023, 1:19pm UTC](https://forum.djangoproject.com/t/model-translations/25323/2 "2023-11-14T13:19:53Z")

</div>

Yep pretty standard related model access from a ` __str__ ()` then suddenly the database is hammered 🙂 Sounds like you’re displaying a list of models somewhere and getting n+1 queries. I usually recommend to people avoiding doing related model lookups from ` __str__ ()`, but hey sometimes practicality beats purity.

You need to make sure the queryset is appropriately setup for this. Please read: [Database access optimization | Django documentation | Django](https://docs.djangoproject.com/en/4.2/topics/db/optimization/#retrieve-everything-at-once-if-you-know-you-will-need-it) and consider using prefetching (all is explained in the docs) 🙂

Happy to answer further Q’s you may have, good luck!

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 1:26pm UTC](https://forum.djangoproject.com/t/model-translations/25323/3 "2023-11-14T13:26:49Z")

</div>

What you’re likely going to want to do here is [annotate](https://docs.djangoproject.com/en/4.2/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset) the `translation` field on to your `Templates` model in the query.

You can do this either in the view where you’re running the query, or if this is something that you’re _always_ going to want to do, do it in a [custom manager](https://docs.djangoproject.com/en/4.2/topics/db/managers/).

Also see [Conditional Expressions | Django documentation | Django](https://docs.djangoproject.com/en/4.2/ref/models/conditional-expressions/)

---

<div class="post-metadata">

**Author:** ![dauid64](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dauid64/32/17084_2.png) [@dauid64](https://forum.djangoproject.com/u/dauid64)\
**Post date:** [November 14, 2023, 1:53pm UTC](https://forum.djangoproject.com/t/model-translations/25323/4 "2023-11-14T13:53:36Z")

</div>

Thanks for the answer, but how i can use prefetch\_related in my model class?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 2:04pm UTC](https://forum.djangoproject.com/t/model-translations/25323/5 "2023-11-14T14:04:37Z")

</div>

You wouldn’t. You would use it in the view where you’re making the query. (Or in a manager or custom queryset as referenced above.)

---

<div class="post-metadata">

**Author:** ![dauid64](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dauid64/32/17084_2.png) [@dauid64](https://forum.djangoproject.com/u/dauid64)\
**Post date:** [November 14, 2023, 2:22pm UTC](https://forum.djangoproject.com/t/model-translations/25323/6 "2023-11-14T14:22:36Z")

</div>

Oh i undestand, i question because i these other models and i try create a form use ModelChoiceField in field template

Models.py

```auto
class TemplateFieldTranslations(models.Model):
    id = models.BigAutoField(primary_key=True)
    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)
    name = models.TextField()
    description = models.TextField()
    template_field = models.ForeignKey('TemplateFields', models.DO_NOTHING)
    language = models.ForeignKey(Languages, models.DO_NOTHING)

    def __str__ (self):
        return self.name

    class Meta:
        managed = False
        db_table = 'template_field_translations'
        unique_together = (('template_field', 'language'),)

class TemplateFields(models.Model):
    id = models.BigAutoField(primary_key=True)
    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)
    deleted_at = models.DateTimeField(blank=True, null=True)
    key = models.TextField()
    data_type = models.TextField()
    template = models.ForeignKey(Templates, models.DO_NOTHING)
    order = models.BigIntegerField(blank=True, null=True)
    use_brand_name = models.BooleanField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'template_fields'

```

forms.py

```auto
class TemplateFieldsForm(forms.ModelForm):
    template = forms.ModelChoiceField(
        queryset=TemplateTranslations.objects.filter(
            language=1).select_related('template'),
        to_field_name="template_id",
        widget=forms.Select(
                attrs={
                    'class': 'select2'
                }
            )
    )

```

and its not pretty show id or object in select options, so i was trying to put the translate, but dont work, return this error

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/d/d/dd624af6e4ab028f110038f511b77139f0f8c6cb.jpeg)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 2:49pm UTC](https://forum.djangoproject.com/t/model-translations/25323/7 "2023-11-14T14:49:13Z")

</div>

That error is caused by this:

> [@dauid64](#):
>
> ```auto
> queryset=TemplateTranslations.objects.filter(
> language=1).select_related('template')
> 
> ```

The `template` field in the `TemplateFields` model is a foreign key to `Templates`, so your queryset must return instances of `Templates`, not `TemplateFields`.

What you’re probably going to want to do here is use the [`iterator`](https://docs.djangoproject.com/en/4.2/ref/forms/fields/#django.forms.ModelChoiceField.iterator) attribute of the ModelChoiceField to create a custom representation of the select options.

You would still have a custom queryset - one that annotates the desired translation in the `Templates` model instances. You would then add the custom subclass as described in the docs to return that annotated value as the display option for that field.

---

<div class="post-metadata">

**Author:** ![dauid64](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dauid64/32/17084_2.png) [@dauid64](https://forum.djangoproject.com/u/dauid64)\
**Post date:** [November 14, 2023, 4:20pm UTC](https://forum.djangoproject.com/t/model-translations/25323/8 "2023-11-14T16:20:56Z")

</div>

Thanks KenWhitesell! it was a great help. I used _iterator_ and worked. I just dont understand still how can i use annotate.
