tortoise / tortoise/tortoise-orm
Using `add()` in a m2m through table with custom fields
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Is your feature request related to a problem? Please describe.
No.
Describe the solution you'd like
When adding data to m2m relationships one usually does
foo = await Foox.create(**data1)
allbars = await Barx.all()
await foo.m2mfield.add(*allbars)
At the moment, the add() method only accepts the using_db=None argument and nothing else (that I know of). If you're using a custom through table which has extra fields other than the basic foox_id and barx_id then you can't use add().
Since one of tortoise's inspirations is the Django ORM, I propose creating a through_defaults argument which allows you to insert that data. It would look something like this
foo = await Foox.create(**data1)
allbars = await Barx.all()
# Custom fields being name and age
await foo.m2mfield.add(*allbars, through_defaults=dict(name='sally', age=22))
Describe alternatives you've considered
Since it's a custom table then the only solution would be insert the data manually with create()
foo = await Foox.create(**data1)
bar = await Barx.create(**data2)
await MyThroughTable.create(foox=foo, barx=bar, name='sally', age=22)
And if you need to insert multiple relationships into the MyThroughTable table then you can use MyThroughTable.bulk_create() instead.
Additional context
If you think this isn't much of a pressing concern atm then I'd be glad to take a look and see if I can make something for it.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start from the many-to-many field's add() entry point and compare it with the create() and bulk_create() paths described in the issue. Support passing through_defaults when creating relationships with custom through-table fields, and verify that the example relationships and extra name and age values are persisted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- database
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100