Search code examples
pythonpeewee

Override select method on peewee


I want to implement soft delete mechanism on peewee.

I tried overriding select method on my BaseModel like save method.

class BaseModel(Model):
    id = BigAutoField()
    created = DateTimeField(default=datetime.datetime.now)
    modified = DateTimeField()
    deleted = BooleanField(default=False)

    def select(self, *args, **kwargs):
        super(BaseModel, self).select(*args, **kwargs).where(BaseModel.deleted!=True)

    def save(self, *args, **kwargs):
        self.modified = datetime.datetime.now()
        super(BaseModel, self).save(*args, **kwargs)

    class Meta:
         database = db

When I try to override select method on my base model it gives following error.

TypeError: select() missing 1 required positional argument: 'self'

Is there any other way to implement soft delete mechanism? What am I missing here?


Solution

  • Don't do this!

    Don't ever do this!

    Instead just add a new classmethod to your model class and use that instead of .select():

    class BaseModel(Model):
        @classmethod
        def public(cls):
            return cls.select().where(cls.deleted != True)
    

    Peewee uses select() internally, and plus, if you choose to override .select() you now have no real way of issuing a query that does not include this filter.