多对多添加数据


发布时间:2019-10-02 13:43    作者: 晖哥哥   已过去:3 年,4 月   阅读总量:1699 已被赞:0


学校表,年级表 都与班级表为多对多关系,怎么绑定他们呢?

前端:

1.传来他们的PK

2.表单验证后

3.后端通过get方法查出相关数据

4.最后使用add方法保存、

def bangding(request):
    if request.method == 'POST':
        form = BangdingForm(request.POST)
        if form.is_valid():
            school = form.cleaned_data.get('school')
            grade = form.cleaned_data.get('grade')
            banji = form.cleaned_data.get('banji')
            ban = Banji.objects.get(pk=banji)
            if ban:
                school= School.objects.get(pk = school)
                grade= Grade_class.objects.get(pk = grade)
                ban.school.add(school)
                ban.grade.add(grade)
                return restful.ok(message='关联成功')
            else:
                return restful.params_error(message='班级代码不正确')
            return restful.params_error(message='关联失败')
        else:
            return restful.params_error(message=form.get_errors())
    else:
        school = School.objects.order_by('-pk')
        grades = Grade_class.objects.order_by('-pk')
        banjis = Banji.objects.order_by('-pk')
        content = {
            'schools': school,
            'grades': grades,
            'banjis': banjis
              }
        return render(request,'cms_grade_class.html',content)

点赞

0




登陆后方可评论