2015-09-19 60 views
0

這裏關係領域是模型如何發佈在DRF

class Event(models.Model): 
    calendar = models.ForeignKey(Calendar) 
    title = models.CharField() 

class Calendar(models.Model): 
    title = models.CharField() 

這裏是串行

class EventSerializer(models.Model): 
    calendarId = serializers.CharField(source='calendar.id') 
    class Meta: 
     model = Event 
     fields = ('id', 'title', 'calendarId') 

class CalendarSerializer(models.Model): 
    class Meta: 
     model = Calendar 
     fields = ('id', 'title') 

然後我嘗試發佈以下JSON下日曆3b60a22c-d46e-46ca-b978-ec81a8b47fcb

{ 
    title:"abc", 
    calendarId:"3b60a22c-d46e-46ca-b978-ec81a8b47fcb" 
} 
創建活動

失敗,出現以下錯誤

ValueError: Cannot assign "{u'id': u'3b60a22c-d46e-46ca-b978-ec81a8b47fcb'}": "Event.calendar" must be a "Calendar" instance.

如何解決這個問題?

+1

見接受的答案在這裏的http:// stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers – fixmycode

回答

0

views.py

class EventViewSet(viewsets.ModelViewSet): 
     serializer_class = EventSerializer 
     queryset = Event.objects.all() 

    def create(self, request, format=None): 
     calendarId = request.data.get("calendarId", None) 
     del request.data["calendarId"] 
     calendar = Calendar.objects.get(id=calendarId) 
     request.data["calendar"] = calendar 
     serializer = EventSerializer(data=request.data) 
     if serializer.is_valid(): 
      serializer.save() 
      return Response(serializer.data) 
     return Response(serializer..errors, status=status.HTTP_400_BAD_REQUEST) 
0

我想你已經創建的類EventSerializer(serializers.ModelSerializer) - (但我你的問題你寫EventSerializer(models.Model))。

反正你應該張貼您的數據是這樣的:

{ 
    title:"abc", 
    calendar:"3b60a22c-d46e-46ca-b978-ec81a8b47fcb" 
} 

,如果不工作,你應填寫日曆字段與日曆對象

def create(self, request, format=None): 
     calendarId = request.data.get("calendarId", None) 
     calendar = Calendar.objects.get(id=calendarId) 
     request.data["calendar"] = calendar 
     ... 
     .. 
     .