我不明白 Django-Rest-Framework 序列化程序是如何工作的
I don't understand how Django-Rest-Framework serializers work
这似乎是一个愚蠢的问题,但我真的觉得 Django-Rest-Framework 并没有很好地解释它是如何工作的。有太多的黑匣子魔法混淆了配置说明(在我看来)。
例如,它说我可以在我的序列化程序中覆盖创建或更新。因此,当我的视图 post 时,我可以将数据发送到声明了更新方法的序列化程序。
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
def update(self, instance, validated_data):
update 是否只在模型已经存在并且我们只是更新其中的一些数据时才被调用?还是在创建新的时调用 create?
如果我要将此方法添加到 class,
def create(self, validated_data):
return MyObject.objects.create(**validated_data)
这是为了添加新对象而必须调用的特定方法吗?并且您的重写能力应该放在序列化程序中,但如果未声明,这是带有正在调用的参数的默认方法吗?
There is too much black box magic which confuses the configuration instructions (in my opinion).
如果文档中有您认为可以改进的地方,请随时 to submit a pull request 进行更新。如果看起来合理,它可能会被合并并出现在未来的版本中。
Or does it call create when it creates a new one?
create
当序列化程序未使用模型实例初始化时调用,但仅将数据传递到其中。一旦 serializer.save()
被调用,序列化程序检查是否传入了实例并直接调用 create
因此模型实例被创建并保存在数据库中。
Does update only get called when the model already exists and we're just updating some of it's data?
update
在使用模型实例(或其他对象)初始化序列化程序时被调用,并且 serializer.save()
被调用。与 Model.objects.create()
.
相比,这大致相当于 Model.objects.update()
is this specifically the method that must be called in order to add a new object?
序列化程序被设计为使用中央 serializer.save()
方法保存(包括对象创建和更新)。这类似于使用 model.save()
方法保存或创建模型的方式。
and your ability to override should be put in the serializer, but if not declared this is the default method with parameters that's being called?
如果您需要更改模型及其相关对象需要保存的逻辑,例如在使用嵌套序列化器。
这似乎是一个愚蠢的问题,但我真的觉得 Django-Rest-Framework 并没有很好地解释它是如何工作的。有太多的黑匣子魔法混淆了配置说明(在我看来)。
例如,它说我可以在我的序列化程序中覆盖创建或更新。因此,当我的视图 post 时,我可以将数据发送到声明了更新方法的序列化程序。
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
def update(self, instance, validated_data):
update 是否只在模型已经存在并且我们只是更新其中的一些数据时才被调用?还是在创建新的时调用 create?
如果我要将此方法添加到 class,
def create(self, validated_data):
return MyObject.objects.create(**validated_data)
这是为了添加新对象而必须调用的特定方法吗?并且您的重写能力应该放在序列化程序中,但如果未声明,这是带有正在调用的参数的默认方法吗?
There is too much black box magic which confuses the configuration instructions (in my opinion).
如果文档中有您认为可以改进的地方,请随时 to submit a pull request 进行更新。如果看起来合理,它可能会被合并并出现在未来的版本中。
Or does it call create when it creates a new one?
create
当序列化程序未使用模型实例初始化时调用,但仅将数据传递到其中。一旦 serializer.save()
被调用,序列化程序检查是否传入了实例并直接调用 create
因此模型实例被创建并保存在数据库中。
Does update only get called when the model already exists and we're just updating some of it's data?
update
在使用模型实例(或其他对象)初始化序列化程序时被调用,并且 serializer.save()
被调用。与 Model.objects.create()
.
Model.objects.update()
is this specifically the method that must be called in order to add a new object?
序列化程序被设计为使用中央 serializer.save()
方法保存(包括对象创建和更新)。这类似于使用 model.save()
方法保存或创建模型的方式。
and your ability to override should be put in the serializer, but if not declared this is the default method with parameters that's being called?
如果您需要更改模型及其相关对象需要保存的逻辑,例如在使用嵌套序列化器。