Django具有多个条件的反向查找外键

时间:2018-10-09 16:25:39

标签: django

我正在尝试在Django中使用多种条件进行反向查找,希望我的问题不会与其他问题重复。让我解释一下:

我有两个模型: 型号A:

import subprocess
import sys
import locale

cmd = "netsh advfirewall show allprofiles"

# returns output as byte string
returned_output = subprocess.check_output(cmd)

# using decode() function to convert byte string to string
print('CMD OUTPUT: ' + returned_output.decode("cp850", "replace"))
# I HAVE CMD ON GERMAN LANGUAGE
# EIN / AUS [GER] for ON / OFF in Domainprofile:
print('CMD OUTPUT: ' + returned_output.decode("cp850", "replace").split("Status")[1].split("Firewallrichtlinie")[0].strip())

if returned_output.decode("utf-8", "replace").split("Status")[1].split("Firewallrichtlinie")[0].strip() == "AUS":
    # set FIREWALL ON ALL PROFILES
    cmd = "netsh advfirewall set allprofiles state on"
    returned_output = subprocess.check_output(cmd)
    print(returned_output.decode("cp850", "replace"))
else:
    # everything ok :)
    sys.exit()

B型:

class A(models.Model):
    title = models.CharField(max_length=200)
    ... other fields

如何获得A: 1)带有标签=名称,值= John的B 2),并且有一个标签为= age,值为= 20

的B

我尝试了以下操作,但不起作用:

class B(models.Model):
    a = models.ForeignKey(A)
    label = models.CharField(max_length=200)
    value = models.CharField(max_length=200)
    ... other fields

1 个答案:

答案 0 :(得分:1)

您可以使用Q object

from django.db.models import Q

A.objects.filter(
    (Q(b__label="name") & Q(b__value="John")) | (Q(b__label="age") & Q(b__value=20))
)