0

I've been researching a lot, but I haven't found a way. I have Document clases with a _owner attribute which specifies the ObjectID of the owner, which is a per-request value, so it's globally available. I would like to be able to set part of the query by default.

For example, doing this query

MyClass.objects(id='12345')

should be the same as doing

MyClass.objects(id='12345', _owner=global.owner)

because _owner=global.owner is always added by default

I haven't found a way to override objects, and using a queryset_classis someway confusing because I still have to remember to call a ".owned()" manager to add the filter every time I want to query something.

It ends up like this...

MyClass.objects(id='12345').owned() 
// same that ...
MyClass.objects(id='12345', _owner=global.owner)

Any Idea? Thanks!

k-ter
  • 958
  • 1
  • 8
  • 20

1 Answers1

1

The following should do the trick for querying (example is simplified by using a constant owned=True but it can easily be extended to use your global):

class OwnedHouseWrapper(object):
    # Implements descriptor protocol

    def __get__(self, instance, owner):
        return House.objects.filter(owned=True)

    def __set__(self, instance, value):
        raise Exception("can't set .objects")


class House(Document):
    address = StringField()
    owned = BooleanField(default=False)

class OwnedHouse:
    objects = OwnedHouseWrapper()

House(address='garbage 12', owned=True).save()
print(OwnedHouse.objects())    # [<House: House object>]
print(len(OwnedHouse.objects)) # 1
bagerard
  • 5,681
  • 3
  • 24
  • 48
  • Hi, thanks, I already tried that way but `objects` is an obj itself. I can’t do for example `len(OwnedHouse.objects)` but I can do `len(House.objects)`, so this solution breaks compatibility with other libraries or components :/ – k-ter Aug 04 '19 at 20:53
  • 1
    I've edited my answer, its possible to improve the previous solution by using the descriptor protocol – bagerard Aug 04 '19 at 21:16