如何在Django中使用through-model访问属性?

时间:2016-04-11 19:37:51

标签: python django django-models

我想弄清楚如何在through-models中使用Django来更轻松地获取属性。我知道如何使用这个models获取一些属性,但它不直观,很难记住如何获取它们。

例如在我的情况下:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')   
    is_translator = models.BooleanField(default=False)
    languages = models.ManyToManyField(Language, through='UserProfileLanguage')

    def __unicode__(self):
        return '{} {}'.format(self.user.first_name, self.user.last_name)

    def __str__(self):
        return '{} {}'.format(self.user.first_name, self.user.last_name)


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

    def __str__(self):
        return self.name

class Level(models.Model):
    LEVEL_CHOICES = (
        ('unknown','Unknown'),
        ('standard','Standard level'),
        ('professional','Professional level'),
        ('native','Native speaker level'),
    )
    name = models.CharField(max_length=40,choices=LEVEL_CHOICES, blank=False, null=False)
    price_multiplier = models.FloatField()

def __str__(self):
    return self.get_name_display()

class UserProfileLanguage(models.Model):
    userprofile = models.ForeignKey(UserProfile)
    language = models.ForeignKey(Language)
    level = models.ForeignKey(Level)

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

例如,当我想知道User是否知道某种语言A时,我必须这样做:

print A in user.userprofile.userprofilelanguage_set.all()

有更简单的方法吗?当我尝试print例如user.userprofile.languages时,它会返回SolutionsForLanguagesApp.Language.None

1 个答案:

答案 0 :(得分:1)

您不应该使用in来搜索某些内容,因为它可能会循环查询集中的所有内容,这很慢。您应该使用exists()

if UserProfileLanuage.objects.filter(user=user, language=A).exists():
    # do something