FastAPI POST/PUT Object with M2M relations
See original GitHub issueIs your feature request related to a problem? Please describe.
I’m using FastAPI in conjuction with Tortoise-orm, together with Pydantic.
With ForeignKeyField it’s pretty easy to add (POST) a new object, since it is treated as a normal field (and this is documented in the generated OPENAPI schema). When it comes to adding an object that has an M2M relation, it gets troublesome. Considering the example of the official docs https://tortoise-orm.readthedocs.io/en/latest/examples/basic.html#relations, one may need to add a new Team participating to an already existing Event. For this case, the generated OPENAPI docs show that one has to first create a new Team and only then add the M2M relation.
The solution is to separately add the M2M relation in a second step, via another path (e.g. /myapi/object/{id}/feature/). This can be done, but it may not be fully executed, leaving, in the case of a connection failure, a half added information. Also, it is not documented how to properly do it (which model should I use?).
Describe the solution you’d like A simple way to add a new object having an M2M relation in an ACID way. That is, all or nothing, especially since APIs rely on HTTP connections which are stateless and may be interrupted suddently.
Describe alternatives you’ve considered A clear and concise description of any alternative solutions or features you’ve considered.
Additional context Add any other context about the feature request here.
Thanks
Issue Analytics
- State:
- Created 3 years ago
- Comments:5

 Top Related Medium Post
Top Related Medium Post Top Related StackOverflow Question
Top Related StackOverflow Question
Well, you can do something like:
What stops me from implementing it, is the fact that I do not know how to implement that, starting from a
tortoise.modeland extending it.There are
fastapidocs, but they do not show how to insert new records in tables along with M2M relations, via an all-or-nothing approach.As an example, one could take the one in the official docs https://tortoise-orm.readthedocs.io/en/latest/examples/basic.html#relations