views:

60

answers:

2

Hi, I was working on a many-to-many model with extra fields and i saw the documentation for extra fields in many to many relations

on their exemple, to create a membership they use

m2 = Membership.objects.create(person=paul, group=beatles,date_joined=date(1960, 8, 1), invite_reason= "Wanted to form a band.")

but that means that they already have the "person" and "group" instances. Normally working in websites we have the id's of the objects... so to create a membership i'd have to do:

person = Person.objects.get(pk=idPerson)
group = Group.objects.get(pk=idgroup)

Now, correct me if i'm wrong but aren't we consulting pointlessly the database two times before the insert? because, all we need in the Membership is the foreign key id's and not the whole object... maybe there's another way to insert in a many-to-many relation using only the id's

+3  A: 

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.

Ofri Raviv
A: 

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.

chefsmart
well... what if you get the id_person and id_group from the POST or GET variables sent by a form? with Ofri Raviv answer i can create the Membership object without having to call the "get" method on each Person and Group objects, that way i'm sure that django hits the db only one time. I'm working with millons of rows, so i want to be sure that im using django the most efficient way =)
pleasedontbelong