這裏關係領域是模型如何發佈在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.
如何解決這個問題?
見接受的答案在這裏的http:// stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers – fixmycode