CustomQueryManager

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.db.models import Manager, Q, QAnd, QOr, QNot

def get_query(obj):
    if isinstance(obj, Manager):
        return obj.query
    return obj

class CustomQueryManager(Manager):
    
    def __init__(self, query=None):
        if query:
            self.query = query
        Manager.__init__(self)
    
    def __and__(self, q):
        return self.__class__(self.query & get_query(q))
    
    def __or__(self, q):
        return self.__class__(self.query | get_query(q))
    
    def not_(self):
        return self.__class__(QNot(self.query))
    
    def get_query_set(self):
        return Manager.get_query_set(self).filter(self.query)

More like this

  1. RandomObjectManager by jjdelc 3 years, 1 month ago
  2. ActiveManager: filter objects depending on publication and/or expiration dates by haplo 5 years, 9 months ago
  3. common model privacy by teepark 6 years, 8 months ago
  4. Custom managers with chainable filters by itavor 6 years, 3 months ago
  5. Filter on Multiple M2M Objects Simultaneously by axiak 7 years ago

Comments

(Forgotten your password?)