StatusField无法使用CreateAPIView

时间:2015-11-04 17:34:05

标签: python-3.x django-views django-rest-framework

以下是我的情况的简化版本:

models.py

from django.db import models
from model_utils import Choices
from django.utils.translation import ugettext_lazy as _
from model_utils.fields import StatusField
...
class Unit(models.Model):
    STATUS = Choices(
        (0, 'new', _('unit is new')),
        (1, 'refurb', _('unit is refurbished')),
        (2, 'scrap', _('unit is scrap')),
    )
    unit_type = StatusField(_('unit type'), default=STATUS.new)
    ...

views.py

class UnitCreateView(generics.CreateAPIView):
    queryset = Unit.objects.all()
    serializer_class = UnitSerializer

    def post(self, request, *args, **kwargs):
        resp = super(UnitCreateView, self).post(request, *args, **kwargs)
        ...

serializers.py

class UnitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Unit
        fields = (..., 'unit_type', ...)

我通过可浏览的api使用帖子。它向我提供了一个表单,我可以在下拉列表中的STATUS属性中选择“新”选项。发送帖子后,我发现resp对象有400个错误的请求错误。

在互动口译中进行调查:

>>> resp.data
{'unit_type': ["Value '0' is not a valid choice."]}

所以似乎UnitCreateView与StatusField不能很好地兼容,否则序列化可能会导致问题。我在这里包含的代码是否存在明显错误?

1 个答案:

答案 0 :(得分:0)

问题解决了:

unit_type = models.IntegerField(_('unit type'), choices=STATUS, default=STATUS.new)