Django 在不使用字段查找的情况下从查询集中排除特定实例
我有时需要确保某些实例从查询集中排除。
这是我通常这样做的方式:
unwanted_instance = MyModel.objects.get(pk=bad_luck_number)
uninteresting_stuff_happens()
my_results = MyModel.objects.exclude(id=unwanted_instance.id)
或者,如果我有更多:
my_results = MyModel.objects.exclude(id_in=[uw_in1.id, uw_in2.id, uw_in3.id])
这“感觉”有点笨拙,所以我尝试了:
my_ideally_obtained_results = MyModel.objects.exclude(unwanted_instance)
这不起作用。但我在这里读到,子查询可以用作排除的参数。
我运气不好吗?我是否缺少一些功能(检查了文档,但没有找到任何有用的指针)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你已经这样做的方式是最好的方式。
如果您正在寻找一种与模型无关的方法,请不要忘记您可以执行
query.exclude(pk=instance.pk)
。顺便说一句,如果 Django 的 ORM 有一个身份映射器(目前没有),那么您将能够执行类似
MyModel.objects.filter(;).all().remove()
,但在这方面你运气不好。您正在做的方式(或上面的方式)是您所拥有的最好的方式。哦,您还可以使用列表理解来比
in
查询做得更好:query.exclude(id__in=[o.id for o in])
The way you're already doing it is the best way.
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)
.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.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>])
给定的答案是完美的,尝试这个对我来说效果很好
步骤1)
步骤2)
The Given answer is perfect and try this which works fine for me
step 1)
step 2)
您可以将不需要的项目放入 list 中,然后获取除列表中的项目之外的所有项目,如下所示:
You can put your unwanted items in a list , and a fetch all items except those in the list like so: