Django DRF - api webview 中的 "hide user"(必填字段)
Django DRF - "hide user" (a mandatory field) in api webview
我有一个简单的模型:
class Store(models.Model):
name = models.CharField("address", max_length = 128, null = True, blank = True)
open = models.PositiveIntegerField("status", default = 1, choices = [(0,0), (1,1)])
user = models.OneToOneField(User, on_delete = models.CASCADE, )
使用简单的序列化程序:
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = ["open", "user"]
观点:
class StateViewSet(viewsets.ModelViewSet):
serializer_class = StoreSerializer
http_method_names = ['get', 'put', 'head']
authentication_classes = [SessionAuthentication,]
permission_classes = [IsAuthenticated,]
def list(self, request):
usr = request.user
stores = Store.objects.filter(user = usr)
return Response(stores.values_list("name", flat = True))
def put(self, request):
usr = request.user
Store.objects.filter(user = usr).update(state = request.data["state"])
return Response("updated")
我想要的是,去掉用户字段——反正只有当前用户可以改变状态,所以它已经是一个预设值了。我知道我省略了名称,因为它是 null = True, blank = True
,但是我怎样才能将 user
预设为 request.user
并让下拉列表消失?
您可以在序列化程序的 Meta 选项中设置 read_only_fields
class
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = ["open", "user"]
<b>read_only_fields = ("user",)</b>
请注意,这只会 exclude/hide 来自 HTML 表格的 user
,不会进行预设。
我有一个简单的模型:
class Store(models.Model):
name = models.CharField("address", max_length = 128, null = True, blank = True)
open = models.PositiveIntegerField("status", default = 1, choices = [(0,0), (1,1)])
user = models.OneToOneField(User, on_delete = models.CASCADE, )
使用简单的序列化程序:
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = ["open", "user"]
观点:
class StateViewSet(viewsets.ModelViewSet):
serializer_class = StoreSerializer
http_method_names = ['get', 'put', 'head']
authentication_classes = [SessionAuthentication,]
permission_classes = [IsAuthenticated,]
def list(self, request):
usr = request.user
stores = Store.objects.filter(user = usr)
return Response(stores.values_list("name", flat = True))
def put(self, request):
usr = request.user
Store.objects.filter(user = usr).update(state = request.data["state"])
return Response("updated")
我想要的是,去掉用户字段——反正只有当前用户可以改变状态,所以它已经是一个预设值了。我知道我省略了名称,因为它是 null = True, blank = True
,但是我怎样才能将 user
预设为 request.user
并让下拉列表消失?
您可以在序列化程序的 Meta 选项中设置 read_only_fields
class
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Store
fields = ["open", "user"]
<b>read_only_fields = ("user",)</b>
请注意,这只会 exclude/hide 来自 HTML 表格的 user
,不会进行预设。