我正在尝试制作一个对客户端和主要用户略有不同的 api。因此,如果角色是客户端,我想稍后添加客户端。
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = models.Store
fields = ["id", "name", "location", "location_lat", "location_lng", "client"]
def create(self, validated_data):
user = self.context["request"].user
if user.role == Roles.CLIENT.name:
validated_data["client"] = user.client
愚蠢的羽绒模看起来像这样
class Store(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
当我现在使用具有角色客户端的用户调用序列化程序时,我得到以下响应:
{"client":["This field is required."]}
这是正确的。但是当我extra_kwargs
添加到StoreSerializer时,发生了奇怪的事情。如果我将序列化程序更改为:
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = models.Store
fields = ["id", "name", "location", "location_lat", "location_lng", "client"]
extra_kwargs = {
"client": { "required": False }
}
def create(self, validated_data):
user = self.context["request"].user
if user.role == Roles.CLIENT.name:
validated_data["client"] = user.client
或将其更改为
class StoreSerializer(serializers.ModelSerializer):
client = serializers.UUIDField(required=False)
class Meta:
model = models.Store
fields = ["id", "name", "location", "location_lat", "location_lng", "client"]
def create(self, validated_data):
user = self.context["request"].user
if user.role == Roles.CLIENT.name:
validated_data["client"] = user.client
我得到同样的回应。这怎么可能?不应该要求客户端吧?
版本:
- 姜戈:2.2.3
- Django rest 框架:3.9.4
商店模型应该是这样的:(注意blank
(
class Store(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True)
现在,在数据库级别,您允许客户端在存储模型中为 null。
序列化程序的方式:
class StoreSerializer(serializers.ModelSerializer):
client = serializers.PrimaryKeyRelatedField(queryset=models.Client.objects.all(), required=False)
class Meta:
model = models.Store
fields = ["id", "name", "client"]
...
序列化程序现在应该可以工作了。
如果你说的是正确的,那么我会跳出那个字段。无论如何,可能是最好的,以便在用户未获得授权时 API 资源管理器不包含它。
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = models.Store
fields = ["id", "name", "location", "location_lat", "location_lng", "client"]
def __init__(*args, **kwargs):
super().__init__(*args, **kwargs)
if self.context["request"].user.role == Roles.CLIENT.name:
del self.fields["client"]
def create(self, validated_data):
user = self.context["request"].user
if user.role == Roles.CLIENT.name:
validated_data["client"] = user.client