Search code examples
pythondjangomany-to-many

update model instance which has m2m fields also


I want to update my model instance using .update(**kwargs) for non-realted fields and .clear() followed by .add() for related fields. My problem is that only one of them is getting executed at a time.

When I do the following its working and updating the m2m fields:

def preview(request):
    worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id))
    worksheet_object.question.clear()
    worksheet_object.question.add(*question_pk_list)
    #other m2m fields

But I want to update the non-related fields also and its not working when I do the following:

def preview(request):
    worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id)).update(
                                        classroom=worksheet_data['classroom'],
                                        category=worksheet_data['category'], 
                                        #other fields)
    worksheet_object.question.clear()
    worksheet_object.question.add(*question_pk_list)
    #other m2m fields

I am using this answer and this answer to do the same in my view.

Can anyone help figure out what I am doing wrong? and how it can be corrected?


Solution

  • There are few issues with the following statement

    WorkSheet.objects.get(pk=int(wsheet_id)).update(
                                        classroom=worksheet_data['classroom'],
                                        category=worksheet_data['category'], 
                                        #other fields)
    
    • update method is available for queryset not for model instance. You are first using get which returns a model instance.
    • For queryset also, update method returns number of rows updated not the object but you require object to update m2m field.

    To solve your issue, you can first get the object, and save it. After that you can update the m2m field.

    def preview(request):
        worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id))
        worksheet_object.classroom=worksheet_data['classroom']
        worksheet_object.category=worksheet_data['category']
        # other fields
        worksheet_object.save()
    
        worksheet_object.question.clear()
        worksheet_object.question.add(*question_pk_list)