Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store list of tuples in Django model?

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:

  • from German to English
  • from Dutch to English

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).

like image 453
Milano Avatar asked Mar 12 '23 19:03

Milano


1 Answers

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 CharFields 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.

like image 134
joshcarllewis Avatar answered Mar 28 '23 21:03

joshcarllewis