In Django ORM, you can write a custom QuerySet
class for your model and then use that queryset instead of a manager, so that you can then chain filtering methods like so:
Users.objects.active(False).created_before(a_month_ago).delete()
Which allows keeping all the knowledge about the structure of the database tables in one place.
Can you do something similar in Tortoise?
For now, I have found the following approach, which feels a bit hacky:
class EventQuerySet(QuerySet):
def by_id(self, id) -> Self:
return self.filter(id=id)
def by_name(self, name) -> Self:
return self.filter(name=name)
class EventManager(Manager):
def get_queryset(self) -> EventQuerySet:
return EventQuerySet(Event)
class Event(Model):
name = fields.CharField(max_length=255)
tournament = fields.ForeignKeyField('models.Tournament', related_name='events')
participants = fields.ManyToManyField('models.Team', related_name='event_team')
objects = EventManager()
And now I can chain my filters:
events = await models.Event.objects.by_name("game one").by_id(2)