发送此字段后,仍然出现“此字段为必填”错误

时间:2019-01-09 06:23:21

标签: django serialization django-rest-framework

class DroneList(generics.ListCreateAPIView):
    queryset = Drone.objects.all()
    serializer_class = DroneSerializer
    name = 'drone-list'
    filter_fields = (
        'name',
        'drone_category',
        'manufacturing_date',
        'has_it_competed',
    )
    search_fields = (
        '^name',
    )
    ordering_fields = (
        'name',
        'manufacturing_date',
    )
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
        custompermission.IsCurrentUserOwnerOrReadOnly,
    )

    def perform_create(self, serializer):
        serializer.save(owner = self.request.user)

Views.py

class DroneSerializer(serializers.HyperlinkedModelSerializer):
# Display the category name
drone_category = serializers.SlugRelatedField(queryset=DroneCategory.objects.all(),
                                              slug_field='name')

owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
    model = Drone
    fields = (
        'url',
        'name',
        'drone_category',
        'manufacturing_date',
        'has_it_competed',
        'inserted_timestamp',
        'owner'
    )


class UserDroneSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
         model = Drone
         fields = (
            'url',
            'name')

Serializer.py

class DroneCategory(models.Model):
    name = models.CharField(max_length=250, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name


class Drone(models.Model):
    name = models.CharField(max_length=250, unique=True)
    drone_category = models.ForeignKey(
        DroneCategory,
       related_name='drones',
       on_delete=models.CASCADE)
    manufacturing_date = models.DateTimeField()
    has_it_competed = models.BooleanField(default=False)
    inserted_timestamp = models.DateTimeField(auto_now_add=True)
       owner = models.ForeignKey(
       'auth.User',
       related_name='drones',
       on_delete=models.CASCADE
)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

models.py

{“名称”:“ Python Drone”,     “ drone_category”:“ Quadcopter”,“ manufacturing_date”:“ 2017-07-      16T02:03:00.716312Z”,“ has_it_competed”:“ false”}

我发送的发帖请求。

django不读取字段,如响应所示: “名称”: [         “这是必填栏。”     ],     “ drone_category”:[         “这是必填栏。”     ],     “生产日期”: [         “这是必填栏。”     ]

1 个答案:

答案 0 :(得分:1)

您需要更改此

class UserDroneSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
         model = Drone
         fields = (
            'url',
            'name',
        'drone_category',
        'manufacturing_date',
        'has_it_competed',
        'inserted_timestamp',
        'owner')