[英]Filter Django Queryset_A with Queryset_B based on a specifict one property with the same value
class Model_A(models.Model):
name = models.CharField()
age = models.CharField()
class Model_B(models.Model):
name = models.CharField()
location = models.CharField()
def some_filter_function():
return [list of Model_A items based on Model_B.name]
考虑到您无法将 Model 更改为使用外键,您可以尝试以下操作:
my_items = []
names = Model_b.objects.all()
for name in names:
name_b = name.name
model_a = Model_a.objects.filter(name = name)
for item in model_a:
my_items.append(item)
我同意@William Van Onsam 的观点。
如果你定义你的Model_A
像
class Model_B(models.Model):
name = models.CharField()
location = models.CharField()
class Model_A(models.Model):
name = models.CharField()
age = models.CharField()
b = models.ForeignKey(Model_B, on_delete=models.CASCADE)
# NOTE you need to declare Model_B prior to Model_A,
# and then you can use Model_B as a parameter here.
然后你可以做
def some_filter_function():
b = get_model_b()
return Model_A.objects.filter(name=b.name)
在您看来 function。
考虑以下方法。
def some_filter_function():
queryset = None
if Model_B.objects.filter(name="Jorge").exists()
queryset = Model_A.objects.all()
return queryset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.