我刚刚实现了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
如何解决此问题?
答案 0 :(得分:0)
我认为您的问题是您尝试add
serializer
而不是Event
实例。
event = serializer.save()
calendar.events.add(event)