在django中检查具有相同m2m关系的对象存在?

时间:2012-08-13 10:39:50

标签: django django-models django-queryset

我有一个这样的模范老师:

name = models.CharField(max_length=100,unique=True)
course = models.ManyToManyField(Course)

课程模式:

course_name = models.CharField(max_length=100,unique=True)

创建Teacher对象时,我想确保我创建的新对象不应与任何其他现有Teacher对象具有相同的课程(m2m关系)。

例如,如果教师对象A具有英语,数学,历史 m2m课程关系,那么没有新的教师对象可以具有英语,数学,历史

查看

def AddTeacher(request):
    #id's are the courses object id
    id1 = request.POST.get('id1')
    id2 = request.POST.get('id2')
    id3 = request.POST.get('id3')


    Tobject  = Teacher(name="temp")
    Tobject.save()

    for i in [id1,id2,id3]:
        Cobject = Course.objects.get(id=i)
        Tobject.course.add(Cobject )
    Tobject.name = "Teacher"+str(Tobject.id)
    Tobject.save()

    temp = {}
    temp['message'] = "Object created successfully"
    return HttpResponse(json.dumps(temp),mimetype="application/json")

3 个答案:

答案 0 :(得分:1)

似乎比较简单。只需查询具有request.POST中指定的所有课程ID的教师,如果有任何结果,请保释:

def AddTeacher(request):
    #id's are the courses object id
    id1 = request.POST.get('id1')
    id2 = request.POST.get('id2')
    id3 = request.POST.get('id3')

    if Teacher.objects.filter(course=id1).filter(course=id2).filter(course=id3).count() > 0:
        return HttpResponseForbidden("Can't add a teacher with these courses; one already exists")

    # ... function continues

这解决了你问题中的确切案例;如果您想处理指定课程是现有教师课程子集的情况(例如,如果您决定允许教师添加两门课程),则需要更多考虑。

答案 1 :(得分:0)

好的,这就是

def AddTeacher(request):
    #id's are the courses object id
    id1 = request.POST.get('id1')
    id2 = request.POST.get('id2')
    id3 = request.POST.get('id3')

    qs = Teacher.objects.all()

    #Build a dynamic filter query
    qs = reduce(lambda q, c: q.filter(course=c), [c for c in [id1, id2, id3]], qs)

    if qs:
        raise ValueError("A teacher with the selected courses already exists")

    teacher  = Teacher(name="temp")
    teacher.save()

    for i in [id1, id2, id3]:
        course = Course.objects.get(id=i)
        teacher.course.add(course)
    teacher.name = "Teacher"+str(teacher.id)
    teacher.save()

    return HttpResponse(json.dumps({
        'message': 'Object created successfully'
    }), mimetype="application/json")

答案 2 :(得分:0)

在相关答案中,但不完全针对这种情况,您可以检查对象是否在m2m中:

if english_course in teacher.courses.all():
    # already in there :)

我只是认为这是一个很好的方法。