Django不使用字段查找来排除来自查询集的特定实例 [英] Django excluding specific instances from queryset without using field lookup

查看:656
本文介绍了Django不使用字段查找来排除来自查询集的特定实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时需要确保某些实例被排除在查询器中。

这是我通常使用的方式:

I sometimes have the need to make sure some instances are excluded from a queryset.
This is the way I do it usually:

unwanted_instance = MyModel.objects.get(pk=bad_luck_number)
uninteresting_stuff_happens()
my_results = MyModel.objects.exclude(id=unwanted_instance.id)

或者,如果我有更多的话:

or, if I have more of them:

my_results = MyModel.objects.exclude(id_in=[uw_in1.id, uw_in2.id, uw_in3.id])

这个感觉有点笨拙,所以我试过:

This 'feels' a bit clunky, so I tried:

my_ideally_obtained_results = MyModel.objects.exclude(unwanted_instance)

哪些不起作用。但是我阅读了一个子查询可以的这里的内容被用作排除的参数。

我运气不好?我错过了一些功能(检查文档,但没有找到任何有用的指针)

Which doesn't work. But I read here on SO that a subquery can be used as parameter for exclude.
Am I out of luck? Am I missing some functionality (checked the docs, but didn't find any useful pointer)

推荐答案

这样做是最好的方法。

如果这是一个模型无关的方法,你正在寻找,不要忘记你可以做 query.exclude(pk = instance.pk)

If it's a model-agnostic way of doing this you're looking for, don't forget that you can do query.exclude(pk=instance.pk).

如同 Django的ORM有一个身份映射程序(它目前没有),那么你可以做一些类似 MyModel.objects.filter(< query>)的所有内容。all()。remove(< instance> ;),但是你在这方面没有运气。你所做的方式(或上面的)是你最好的。

Just as an aside, if Django's ORM had an identity mapper (which it doesn't at present), then you would be able to do something like MyModel.objects.filter(<query>).all().remove(<instance>), but you're out of luck in that regard. The way you're doing it (or the one above) is the best you've got.

哦,你也可以做得比这更好$ c>在查询中使用列表推导: query.exclude(id__in = [o.id for o in< unused objects>])

Oh, and also you can do much better than that in query with a list comprehension: query.exclude(id__in=[o.id for o in <unwanted objects>])

这篇关于Django不使用字段查找来排除来自查询集的特定实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆