How to save a ManyToMany field with a through relationship
for django 1.x, it is as what Rahul said that you can't use add
, create
, etc
for django 2.x, you actually can per the document here django 2.x
You can also use add(), create(), or set() to create relationships, as long as you specify through_defaults for any required fields:
beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)}) beatles.members.create(name="George Harrison", through_defaults={'date_joined': date(1960, 8, 1)}) beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})
You will have to explicitly save the MeetingArrival
object in your view to save an intermediate model in case of a ManyToManyField
with through
argument.
For Django versions 2.1 and below, in case of ManyToManyField
with an intermediary model, you can’t use add
, create
, or assignment
which are available with normal many-to-many fields.
As per the Django 1.8 docs:
Unlike normal many-to-many fields, you can’t use add, create, or assignment to create relationships.
The only way to create this type of relationship is to create instances of the intermediate model.
So, you will have to explicitly create a MeetingArrival
object in your view.
You can do it by:
def add_meeting(request):
add_meeting_form = AddMeetingForm(request.POST or None)
site = Site.objects.get(user=request.user.id)
if request.method == "POST":
if add_meeting_form.is_valid():
obj = add_meeting_form.save(commit=False)
obj.site = site
obj.save()
# create an instance of 'MeetingArrival' object
meeting_arrival_obj = MeetingArrival(meeting=obj, visitor=<your_visitor_object_here>, arrival_status=True)
meeting_arrival_obj.save() # save the object in the db
When you use a through table, you need to save there manually.
MeetingArrival.objects.create( ... )