从序列化程序创建实例而不将其持久保存到db

时间:2016-01-25 23:25:49

标签: python django django-rest-framework

creating a django model

的上下文中工作
# Creates potato and saves a row to db
spud = Potato.objects.create(...)

# Also creates a potato instance, but doesn't hit db yet.
# Could call `spud.save()` later if/when we want that.
spud = Potato(...)

factory boy中,我们也对这个Djangoism进行了类比

# Returns a saved instance
spud = PotatoFactory.create()

# Returns an instance that's not saved
spud = PotatoFactory.build()

rest framework v3.3.2中,我无法找到类比。有可能吗?

serializer = PotatoSerializer(data=...)

# creates the instance and saves in db
serializer.create(serializer.validated_data)

我可以写自己的东西,如下:

class PotatoSerializer:
    ...
    def build(self, validated_data):
        return self.Meta.model(**validated_data)

但是如果没有将它放在基本序列化程序上,我会错过一些东西吗?

3 个答案:

答案 0 :(得分:0)

默认Serializer会保存到数据库。但是,如果要对验证进行测试,只需调用is_valid即可,避免保存到数据库。

我大多猜测你的问题并不是很清楚你的目标。

答案 1 :(得分:0)

在PotatoSerializer中

,您需要覆盖Create方法。 像这样的东西:

class PotatoSerializer:
    ...
    class Meta:
        ...

    def create(self, validated_data):
        # and here you change the default behavior of the serializer
        return Potato(**validated_data)
            # instead of
            # return Potato.objects.create(**validated_data)

答案 2 :(得分:0)

来自https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L811-L846(评论已省略):

def create(self, validated_data):
    raise_errors_on_nested_writes('create', self, validated_data)

    ModelClass = self.Meta.model

    info = model_meta.get_field_info(ModelClass)
    many_to_many = {}
    for field_name, relation_info in info.relations.items():
        if relation_info.to_many and (field_name in validated_data):
            many_to_many[field_name] = validated_data.pop(field_name)

    try:
        instance = ModelClass.objects.create(**validated_data)

序列化程序create()方法是模型create()方法的一个相当薄的包装器。

坏消息是你是对的,没有仅限内存的序列化程序快捷方式:

class PotatoSerializer:
    ...
    def build(self, validated_data):
        return self.Meta.model(**validated_data)

好消息是你可以切断中间人并直接打电话给模特:

Potato(**validated_data)