Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model.save() not called when loading Django fixtures?

I am overriding my Django model save() method, so I can do some extra sanity checking on the object. (Is save() the correct place to do this?)

It doesn't appear that my fixtures/initial_fixtures.yaml objects have their save() method called. How can I sanity-check my fixtures?

like image 387
Joseph Turian Avatar asked Oct 24 '11 18:10

Joseph Turian


People also ask

How to load data from fixtures in Django?

You can load data by calling manage.py loaddata <fixturename> , where <fixturename> is the name of the fixture file you've created. Each time you run loaddata , the data will be read from the fixture and reloaded into the database.

What does save () do in Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

Does Django objects create call save?

Does Django objects create call save? Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .


2 Answers

As of Django 1.5, save() is NOT called:

When fixture files are processed, the data is saved to the database as is. Model defined save() methods are not called, and any pre_save or post_save signals will be called with raw=True since the instance only contains attributes that are local to the model.

https://docs.djangoproject.com/en/1.9/ref/django-admin/

like image 89
Emil Stenström Avatar answered Sep 17 '22 15:09

Emil Stenström


The .save() method is called during fixture loading as seen in https://code.djangoproject.com/browser/django/tags/releases/1.3.1/django/core/management/commands/loaddata.py?rev=17029#L174

If you use a different DJ version, you can check that but I'm quite sure it is called in older versions as well.

How are you checking if your objects have their save() method called?

And about doing this in .save(), if the sanity checks are non-trivial then I don't think it's a very good idea.

like image 22
Botond Béres Avatar answered Sep 17 '22 15:09

Botond Béres