To better explain my question, let's consider that I have an application that supports multiple languages, let's see this code example:
class SomeModel(models.Model):
title = models.CharField(max_length=255) # kept for backward comnpatibility only
title_en = models.CharField(max_length=255)
title_fr = models.CharField(max_length=255)
...
knowing that the current language is English (en - got it by using django.utils.translation.get_language
), I execute this query:
SomeModel.objects.get(title="some title")
which produces this SQL query:
SELECT * FROM some_models WHERE title='some title';
However, what I'm looking for is a way to to automatically produce a query like this based on the current language without changing the ORM query above:
# when language is English:
SELECT * FROM some_models WHERE title_en='some title';
# when language is French:
SELECT * FROM some_models WHERE title_fr='some title';
I've tried using annotations but Django doesn't allow overriding a field that is already defined in the model.
Bear in mind that the solution I'm searching for needs to work with other methods like filter
and values_list
and so on.
Instead of having separate fields for each language, create a single model field to store the title and another field for language type choices (e.g., 'en' for English, 'fr' for French). `
from django.db import models from django.utils.translation import get_language
class SomeModel(models.Model):
title = models.CharField(max_length=255)
language = models.CharField(max_length=255, choices=[('english', 'English'), ('frrench', 'French')])
current_language = get_language()
SomeModel.objects.get(title_en="some title", language=current_language) `
This approach allows scalability as you can easily add support for additional languages without modifying the model structure.
It also provides flexibility in querying, allowing you to filter, exclude, or perform other operations based on the language type.