tortoise / tortoise/tortoise-orm

Using `add()` in a m2m through table with custom fields

Open
#692 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.