错误在只写字段选项中。这个
required
参数默认值设置为
True
如果我们看一下模型的话,目的是不需要它。在这个视图中,我使用perform_create作为后期处理保存在model db表示上。自从
必修的
默认值为
真的
在创造层面,第一个
.save()
到数据库失败。因为这纯粹是内部逻辑,所以不需要。所以简单地添加
required=False
上的选项
PrimaryKeyRelatedField
工作是:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
class ProjectSerializer(serializers.ModelSerializer):
created_by = UserSerializer(read_only=True)
created_by_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source='created_by', write_only=True, required=False)
class Meta:
model = Project
fields = ('project_id', 'created_by', 'created_by_id', 'created')
如果我坚持纯粹在序列化器级别使用逻辑进行反序列化,那么在模型级别强制required=true也需要重写序列化器的.save函数。可能有一种方法可以在序列化程序中获取用户引用,并使视图实现更加“默认”…这可以通过使用
Jerin
以下内容:
class ProjectSerializer(serializers.ModelSerializer):
created_by = UserSerializer(read_only=True)
created_by_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source='created_by',
write_only=True,
required=False,
default=serializers.CurrentUserDefault())
class Meta:
model = Project
fields = ('project_id', 'created_by', 'created_by_id', 'created')
现在要仅使用username格式化json,需要使用slug字段而不是userserializer:
class ProjectSerializer(serializers.ModelSerializer):
created_by = serializers.SlugRelatedField(
queryset=User.objects.all(), slug_field="username")
created_by_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source='created_by', write_only=True, required=False)
class Meta:
model = Project
fields = ('project_id', 'created_by', 'created_by_id', 'created')
然后,只有用户模型的username字段值将显示在get负载的create_by json标记上。
更新-1
在这里做了一些调整之后,我得出了最终版本:
class ProjectSerializer(serializers.ModelSerializer):
created_by_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), write_only=True, required=False, default=serializers.CurrentUserDefault())
created_by = serializers.SerializerMethodField('creator')
def creator(self, obj):
return obj.created_by_id.username
class Meta:
model = Project
fields = ('project_id', 'created_by_id', 'created_by', 'created')