Is it possible to store field of tuples of Model
in Django? In my case, I have a model Translator. The translator should store information about what languages he can translate. But there may be situation that translator can't translate from English to German but he/she can do that in opposite direction.
So one object translator could store this:
but he can't translate from English to German or Dutch.
So what I probably looking for is to store field of tuples of Models (there is a model called Language).
The solution I recommend would be to create a model to represent each one-way translation and then use a ManyToManyField
relationship.
For example:
class LanguagePair(models.Model):
from_language = models.CharField(max_length=220)
to_language = models.CharField(max_length=220)
class Translator(models.Model):
languages = models.ManyToManyField('LanguagePair')
...
So each Translator would have multiple LanguagePair objects associated with it that represents the languages they can translate.
This would allow you to easily query for all Translators that can translate a particular language as the actual translation is an object. I would also recommend that instead as storing languages in CharField
s you actually make another Language
model and change the LanguagePair
model to have two ForeignKey
fields to the language.
An alternative solution would be to serialise the list or languages pairs from a standard python list and store it as a JSON string in a CharField
but this would make things harder for queries and could be a problem in the future. It's generally a good idea to not be afraid of separating logic out into separate models as this leads to a more flexible and scalable approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With