Bulk create for realtions #243
Unanswered
luisjimenez6245
asked this question in
Q&A
Replies: 1 comment
-
If both of your sides are saved (and I assume it's true from your snipper) you can simply manually bulk_create the through model, which is a simple ormar model too. So if you provided the through model in your ManyToMany declaration you already have it. ThroughModel = Song.Meta.model_fields["categories"].through Now that you have the through model is as simple as: categories:List[Category]= await Category.objects.all()
song:Song = await Song.objects.get(id = 0)
# note that this assumes that you didn't customize through relation fields, if applicable change the param names
# you can also simply pas song id (0 in this case) and not fetch the song at all
# if your through model have additional fields you can pass them here too
through_instances = [ThroughModel(song=song.pk, category=category.pk) for category in categories]
# bulk create the through models
await ThroughModel.objects.bulk_create(through_instances) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is there a way to excuse bulk create in a ManyToMany relation?
I don´t care about retrieving again my info, but it could be cool If it could be a way to insert many items to a relation.
Here´s an example of the code im trying to explain
`
categories:List[Category]= await Category.objects.all()
song:Song = await Song.objects.get(id = 0)
await song.categories.bulk_save(categories)
`
Beta Was this translation helpful? Give feedback.
All reactions