Django - 如何过滤ManyToMany关系?

时间:2016-11-16 18:46:13

标签: python django django-models

我的项目中有一个Translator模型。此模型包含ManyToManyField languages_verified(verbose_name ='users_languages_verified')和languages_not_verified。我想获取至少一个Language集合的所有languages_verified个对象。

所以如果翻译x和y:

x.languages_verified = ['FR','EN']
x.languages_not_verified = ['RU','SK']
y.languages_verified = ['RU']
y.languages_not_verified = ['SK','CZ']

然后输出将是['FR','EN','RU'](不是'SK'也不是'CZ',因为它们不在至少一个languages_verified集中)

有可能以这种方式做到这一点:

lang_ver_set = []
for language in Language.objects.all():
    for translator in Translator.objects.all():
        if language in translator.languages_verified():
            lang_ver_set.append(language)
            break

但我不确定这是否是一种最有效的方法。 Django有很多像verbose_name__in...这样的魔术过滤技巧,可能会更快,但我找不到解决方案。

1 个答案:

答案 0 :(得分:1)

你应该能够使用反向关系。

$c = Get-Credential -credential ${CREDENTIAL}

$loginbase = 'http://${IP}'
$loginURL = $loginbase + '/AdminTools/querybuilder/'
$r = Invoke-WebRequest -Uri ($loginURL + 'logonform.jsp') -SessionVariable session

$form = $r.Forms[0];

$form.Fields['aps'] = '${Node.DNS}:6400';
$form.Fields['usr'] = $c.Username;
$form.Fields['pwd'] = SecureStringToString $c.Password;

$r = Invoke-WebRequest -Uri ($loginURL + $form.Action) -Method POST -Body $form.Fields -WebSession $session;