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=i开发者_JS百科dPerson)
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
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.
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.
精彩评论