Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance from serializer without persisting it to db

Working in the context of 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(...)

In factory boy we also have an analogy for this Djangoism

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

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

In rest framework v3.3.2, I can't find the analogy. Is it possible?

serializer = PotatoSerializer(data=...)

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

I can write my own, something like this:

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

But it's a drag not to have it on the base serializer, am I missing something?

like image 276
wim Avatar asked Jan 25 '16 23:01

wim


1 Answers

Default Serializer do save to the database. However, if you want to test against the validation, a simple call to is_valid will do and avoid saving to the database.

I'm mostly guessing as your question isn't very clear regarding your goal.

like image 173
Linovia Avatar answered Nov 03 '22 20:11

Linovia