tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

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

Open enchance opened this issue 4 years ago • 0 comments

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.

enchance avatar Mar 31 '21 12:03 enchance