Home > Mobile >  Create model instance consisting of many-to-many field
Create model instance consisting of many-to-many field

Time:11-22

I am trying to create a model instance using a post request, however one issue that I am having is that the model consists of a field which is of many-to-many. Now I am at a stage where I have got an array consisting of primary keys of the model instances (Modules) I wish to associate with the model I am trying to create (a Student).

Please see my code below as I do not know where I am going wrong, after some basic research it seems I need to use a .set() method.

The PUT['modules'] corresponds to array that consists of values [1,2,3,5].

def create_student(request):
    """API for creating a student"""
    if request.method == "POST":
        PUT = json.loads(request.body)
        student = Student(name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year'],
                          modules=PUT['modules'] # THIS IS WHERE I NEED HELP
                          )
        student.save()
        return JsonResponse(student.to_dict())

    return HttpResponseBadRequest("Invalid method")

Thank you for your time.

CodePudding user response:

In order to populate a ManyToManyField relation, first the two items that you want to link need to be saved. This is necessary since otherwise these do not have a primary key: one links two items by adding a record in the junction table with the two primary keys to link.

If you thus want to link the Student you are constructing with the modules, you first create the student, and then you can use student.modules.add(…) to link it to the (existing) modules by unpacking a list of the primary keys of the modules:

def create_student(request):
    """API for creating a student"""
    if request.method == "POST":
        PUT = json.loads(request.body)
        student = Student.objects.create(
            name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year']
        )
        student.modules.add(*PUT['modules'])
        return JsonResponse(student.to_dict())
    else:
        # …
  • Related