如何使用django-rest-framework添加manytomanyfield

时间:2015-08-29 14:02:31

标签: django django-rest-framework

我刚刚实现了ModelViewSet类的create方法。在此函数中,我将创建一个新对象Event,并将其添加到另一个对象events的manytomanyfield Calendar,这是我的代码:

def create(self, request, calendar_pk=None):
    calendar = get_object_or_404(Calendar, guid=calendar_pk)
    serializer = EventSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()

        # if remove this two lines, it works well 
        calendar.events.add(serializer)
        calendar.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

它只是提升到异常

之下
IntegrityError
(1062, "Duplicate entry 'e1c4570899d149e8b093773feb208328-EventSerializer(data=<QueryDict' for key 'calendar_id'")
/usr/lib/python2.7/dist-packages/MySQLdb/connections.py in defaulterrorhandler, line 36

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您尝试add serializer而不是Event实例。

event = serializer.save()
calendar.events.add(event)