简体   繁体   English

如何获得Django .filter(something__in = some_set)查询的* UN *匹配条件?

[英]How can I get the *UN*matched criteria for a Django .filter(something__in=some_set) query?

Not infrequently, I find myself with a set of identifiers and want to retrieve all the objects in a table that match any of the identifiers, but also want to see all the identifiers that didn't have any matched objects in the database. 我经常会找到一组标识符,并希望检索表中与所有标识符匹配的所有对象,但希望查看数据库中没有任何匹配对象的所有标识符。

The way I do this now is: 我现在这样做的方式是:

some_ids = ("a", "b", "c")
matched_objects = MyModel.objects.filter(my_key__in=some_ids)
caught_ids = set()
for obj in matched_objects:
    caught_ids.add(obj.my_key)
unmatched_ids = set(some_ids) - caught_ids

This feels very verbose. 这感觉很冗长。 Is there a better way to do this? 有一个更好的方法吗?

For the second part of your question get distict values for your my_key field 对于问题的第二部分,获取my_key字段的my_key

caught_ids = matched_objects.values_list('my_key').distinct()

then get unmatched_ids just like you did before. 然后像以前一样获取unmatched_ids

unmatched_ids = set(some_ids) - set(caught_ids)

Your code would look like this: 您的代码如下所示:

some_ids = ("a", "b", "c")
matched_objects = MyModel.objects.filter(my_key__in=some_ids)
caught_ids = matched_objects.values_list('my_key').distinct()
unmatched_ids = set(some_ids) - set(caught_ids)
# Get a list of keys that match your IDs

some_ids = set(some_ids)
keys = set(MyModel.objects.filter(my_key__in = some_ids).values_list('my_key',flat=True))

Presumably keys will contain all those IDs that existed in some_ids . 大概keys将包含some_ids中存在的所有那些ID。 Now we can use typical set operations to identify those elements that match or don't match. 现在,我们可以使用典型的设置操作来识别匹配或不匹配的元素。 There are a number of examples here ( http://docs.python.org/2/library/sets.html#set-objects ) but from your comment, it sounds like you want: 这里有许多示例( http://docs.python.org/2/library/sets.html#set-objects ),但从您的评论看来,这听起来像是您想要的:

unmatched = some_ids not in keys 

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

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