Django:获取查询集的补充 [英] Django: Getting complement of queryset

查看:105
本文介绍了Django:获取查询集的补充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了某个模型的查询集,我想得到它的补充,即该模型的所有实例在上述查询集中不是 .

I get a queryset for a certain model and I'd like to get its complement, i.e. all instances of that model that are not in the aforementioned queryset.

我该怎么办?

推荐答案

简短解决方案

qs = Model.objects.filter(...) # qs with objects to exclude
result = Model.objects.exclude(pk__in=qs.values_list('pk', flat=True))

更多DRY解决方案

但是,如果您想多次使用该逻辑,我建议将其封装在一个方法中.这是我自定义查询集中使用的一个示例:

However, if you want to use the logic many times, I would suggest to encapsulate it in a method. Here is an example I personnaly used in a custom queryset:

class QuerysetUtils:
    def get_queryset_complement(self, method):
        return self.exclude(pk__in=method().values_list('pk', flat=True))


class ExpirableQueryset(QuerysetUtils, models.query.QuerySet):
    def expired(self):
        return self.filter(expiration__lte=timezone.now())

    def unexpired(self):
        return self.get_queryset_complement(self.expired)

这篇关于Django:获取查询集的补充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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