gpt4 book ai didi

DJango REST Framework 只读字段

转载 作者:行者123 更新时间:2023-12-03 21:16:57 24 4
gpt4 key购买 nike

我有一个字段 owner那是一个 ForeignKeyUser模型。

此字段是 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

最佳答案

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

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

关于DJango REST Framework 只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com