简体   繁体   中英

How to store field of tuples of models in Django models?

I'm working on a web for translators. I'm stucked on designing a structure of the data. So there is a model Translator, Language and Level. The price depends on Language and Level (Standard level multiplies the price 1x, Professional 1.5x etc.)

Each Translator can translate multiple languages with different levels (skills).

I can't figure out how to design models for this purpose. My idea is to store for each Translator some field of tuples (Language,Level) so the model Translator would be:

class TranslatorProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    date_of_birth = models.DateField(null=True,blank=True)
    telephone = models.CharField(max_length=40,null=True,blank=True)
    IBAN = models.CharField(max_length=40,null=True,blank=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    # HERE IS THE PROBLEM
    languages = models.FieldOfModelTuples(Language,Level)

class Level(models.Model):
     LEVEL_NAMES = (
            ('standard', 'Standard'),
            ('professional', 'Professional'),
            #etc.
        )
    name = models.CharField(max_length=40, choices=LEVEL_NAMES)
    price_multiplier = models.FloatField()

class Language(models.Model):
    shortcut = models.CharField(max_length=40)
    name = models.CharField(max_length=40)

    def __str__(self):
        return self.name

I would appreciate any advice how to solve this problem (. FieldOfModelTuples does not exists of course). Maybe there is a simpler way to do this.

I think that Level should be a field on a through-model for a many-to-many relationship between TranslatorProfile and Language :

class TranslatorLanguage(models.Model):
    translator = models.ForeignKey('app_name.TranslatorProfile')
    language = models.ForeignKey('app_name.Language')
    level = models.ForeignKey('app_name.Level')

    class Meta:
        unique_together = (('translator', 'language'),)

this allows you to query all necessary properties for each Translator - Language pair. Access to a translator's languages can then be simplified via:

# HERE IS THE PROBLEM
languages = models.ManyToManyField(Language, through='TranslatorLanguage')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM