简体   繁体   English

ORM 如何准确过滤带有参数列表的查询?

[英]How to ORM filter a query with parameter list exactly?

I have a query filter我有一个查询过滤器

query_1 = Model.objects.filter(param = param)

I need to filter this list to another ORM and return true or flase only if all the data in the query_1 is in the second query.我需要将此列表过滤到另一个 ORM 并且仅当 query_1 中的所有数据都在第二个查询中时才返回 true 或 flase。 Like,喜欢,

query_2 = AnotherModel.objects.filter(field__in=query_1)

return True only if all the objects in the query_1 list is in the query_2.仅当 query_1 列表中的所有对象都在 query_2 中时才返回 True。

I don't think it can be done using only ORM.我认为仅使用 ORM 是无法做到的。 If field is foreignkey to Model:如果field是 Model 的外键:

def my_func(param):
  list_of_ids_1 = Model.objects.filter(param = param).values_list('id', flat=True)
  list_of_ids_2 = AnotherModel.objects.filter(field__in=list_of_ids_1).values_list('field_id', flat=True).distinct()

  return len(list_of_ids_1) == len(list_of_ids_2)

Lets assume Model , AnotherModel are like this让我们假设ModelAnotherModel是这样的

class Model(models.Model):
    param=models.CharField(...)
    ...

class AnotherModel(models.Model);
    field = models.ForeignKey(Model, on_delete=...)  
    ...  
    

Then the following query will return only those Model which have corresponding AnotherModel然后下面的查询将只返回那些Model有相应AnotherModel

result = Model.objects.filter(param=param, anothermodel__isnull=False)

but if you want to check the filter(param=param) result if there is any model which is not present in AnotherModel , you have to do it manually但是如果您想检查filter(param=param)结果是否存在 AnotherModel 中不存在的AnotherModel ,则必须手动进行

exists = true
query_1 = Model.objects.filter(param = param)
for model in query_1:
    if not AnotherModel.objects.filter(field=model).exists():
        exists = false
        break

# if exists is true that means all of the query_1 obj is there in AnotherModel 

You can check if there is any Model for which there is no AnotherModel with:您可以检查是否有没有其他AnotherModel Model

not Model.objects.filter(anothermodel=None).exists()

if the query returns True then not … will thus return False and this means that all Model s are referenced by AnotherModel and vice versa.如果查询返回True那么not …将因此返回False ,这意味着所有Model都被AnotherModel引用,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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