DJango REST框架只读字段

时间:2017-04-04 10:47:30

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

我的字段ownerForeignKeyUser模型。

此字段在创建时为required。但它以后不能改变。

如何制作字段Non-Editable?除了创建多个序列化器之外还有其他方法吗?

车库模型

class GarageDetails(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, )
    name = models.CharField(_('Garage Name'), max_length=254, blank=False, null=False, unique=True)
    price = models.IntegerField(_('Price'), blank=False)
    available_from = models.TimeField(_('Available From'), default=datetime.time(6, 00), blank=False)
    available_till = models.TimeField(_('Available till'), default=datetime.time(18, 00), blank=False)
    description = models.TextField(_('Garage Description'), blank=True, null=True)

    create_date = cmodels.UnixTimestampField(_('Date Added'), auto_now_add=True)
    update_date = cmodels.UnixTimestampField(_('Date Added'), auto_created=True)
    is_available = models.BooleanField(_('Available'), default=True)

串行

class UserFKSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('id', 'name', 'email', 'mobile')


class GarageSerializer(serializers.ModelSerializer):
    owner = UserFKSerializer(many=False, read_only=True)

    class Meta:
        model = GarageDetails
        fields = '__all__'
        read_only_fields = ('id', 'owner', 'create_date', 'update_date')

浏览

class GarageRegister(generics.ListCreateAPIView):
    renderer_classes = (JSONRenderer, )
    permission_classes = (IsAuthenticated, )

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        serialize = GarageSerializer(data=request.data)
        if serialize.is_valid():
            # Create Garage with owner & name

class GarageUpdate(generics.ListCreateAPIView):
    renderer_classes = (JSONRenderer, )
    permission_classes = (IsAuthenticated, )

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        serialize = GarageSerializer(data=request.data)
        if serialize.is_valid():
            # Update Garage but can't update create_date, id, owner & name

2 个答案:

答案 0 :(得分:2)

您可以为每个用例创建不同的模型序列化程序(更新,创建):

在模型序列化程序中的read_only_fields中指定该字段:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('a', 'nother', 'field')
        read_only_fields = ('owner',)

对于django表单,您可以设置disabled field

class MyModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super().__init__(*args, **kwargs)
       form.fields['owner'].widget.attrs['disabled'] = True

答案 1 :(得分:0)

您可以通过如下重写“ update”方法来做到这一点:

  def update(self, instance, validated_data):                                                     
      if 'owner' in validated_data:                                                              
          del validated_data['owner']                                                            
      return super().update(instance, validated_data)

这将在更新时默默地忽略所有者字段。如果愿意,您可以改为“提高ValidationError('可能未在更新时设置所有者')”,但是如果这样做,您可能希望读取模型实例,并且仅在实际发生更改时才提出错误,以避免误报。

此外,如果您使用的是python2,则“ super”调用必须为“ super(GarageSerializer,self)”或类似名称。