Django REST Framework ModelField requires 'mod

2019-08-08 10:59发布

问题:

I'm kind of new to Django REST Framework. I'm getting this weird error that is probably caused by something simple, I write 'weird' cause I googled it several times and couldn't find any reference.

model:

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)
    ...

serializer:

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")

view:

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

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

urls:

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

The POST request comes from backbone and the JSON all it has is a dict:{"activity":"1"}. What am I missing? The view is supposed to create a new Records object with the activity ForeignKey Field set to the activity received in the POST request and save it.

The error I get is:

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

回答1:

Your serializer base class is wrong. It should be ModelSerializer instead of ModelField.

from rest_framework import serializers

class RecordSerializer(serializers.ModelSerializer):
    # serializer implementation