Skip to content

How to define and use relational filter attribute for tortoise-orm #569

@xalien10

Description

@xalien10

I was wondering how we can filter models by using relational attributes in the tortoise-orm.

For instance here are the database models-

from tortoise import fields
from tortoise.models import Model


class Tournament(Model):
    id = fields.IntField(primary_key=True)
    name = fields.TextField()
    desc = fields.TextField(null=True)

    events: fields.ReverseRelation["Event"]

    def __str__(self):
        return self.name


class Event(Model):
    id = fields.IntField(primary_key=True)
    name = fields.TextField()
    tournament: fields.ForeignKeyRelation[Tournament] = fields.ForeignKeyField(
        "models.Tournament", related_name="events"
    )
    participants: fields.ManyToManyRelation["Team"] = fields.ManyToManyField(
        "models.Team", related_name="events", through="event_team"
    )

    def __str__(self):
        return self.name


class Team(Model):
    id = fields.IntField(primary_key=True)
    name = fields.TextField()

    events: fields.ManyToManyRelation[Event]

    def __str__(self):
        return self.name

From the above Event model what I need to do to filter by tournament__name="demo". How should I define Event Filterset. Can you please give a little bit of hints?

Should I need to define both the TournamentFilterSet and EventFilterSet and then within EventFilterSet for the field tournament should we point the TournamentFilterSet?

Can you please give us an example? And it would be great to see some nested filtering example in the example doc

@uriyyo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions