[Django]-Correct way to insert Many-to-Many objects in Django?

4👍

You can use

Membership.objects.create(person_id=person_id, group_id=group_id)

where person_id and group_id are the ids of the objects you want to link.

0👍

Well, where are you getting id_person or id_group from? They wouldn’t exist without the person or group they belong to, right? I mean to get to the id of the person, you would start at the person that you can already access.

While using Django, you can safely stop thinking in terms of the database and align your thoughts more along the objects that you have at your disposal.

Anyway, Django doesn’t hit the database unless it encounters the point where it absolutely has to.

Leave a comment