1

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

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

和课程模型:

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

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

例如,如果 Teacher 对象 A 有English,Maths,History m2m Course 关系,那么没有新的 Teacher 对象可以有English,Maths,History

看法

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")
4

3 回答 3

1

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

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

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

于 2012-08-13T17:51:56.100 回答
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")
于 2012-08-13T13:21:55.150 回答
0

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

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

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

于 2013-05-19T15:44:35.640 回答