Django REST框架ModelField需要' model_field' kwarg

时间:2014-11-20 01:57:26

标签: django django-rest-framework

我是Django REST Framework的新手。我得到的这个奇怪的错误很可能是由一些简单的事情引起的,我写的很奇怪'因为我用Google搜索了几次而无法找到任何参考资料。

模型:

class Records(models.Model):
    owner = models.ForeignKey(User, null=True)
    activity = models.ForeignKey(Activity, null=True)
    time_start = models.DateTimeField(null=True)
    time_end = models.DateTimeField(null=True)
    ...

串行器:

class RecordSerializer(serializers.ModelField):
    activity = serializers.PrimaryKeyRelatedField()
    now = datetime.today()
    owner = serializers.CharField(source='owner.username', read_only=True)
    time_start = serializers.DateTimeField(source='now')

    class Meta:
        model = Records
        fields = ("owner", "activity", "time_start")

视图:

class StartApiView(generics.CreateAPIView):
    model = Records
    serializer_class = RecordSerializer

    def pre_save(self, obj):
        obj.owner = self.request.user

网址:

urlpatterns = patterns('',
    # Today app
    url(r'^today/$', views.TodayView.as_view(), name='today'),
    url(r'^start/$', views.StartApiView.as_view(), name='start'),
    ...

POST请求来自主干,它所拥有的JSON是一个dict:{"activity":"1"}。我错过了什么?该视图应该创建一个新的Records对象,其活动ForeignKey Field设置为POST请求中接收的活动并保存。

我得到的错误是:

ValueError at /times/start/
ModelField requires 'model_field' kwarg

1 个答案:

答案 0 :(得分:4)

您的序列化程序基类错误。它应该是 ModelSerializer 而不是ModelField。

from rest_framework import serializers

class RecordSerializer(serializers.ModelSerializer):
    # serializer implementation