2010-07-09 21 views
7

Czy metody składowania save() są leniwe w django?Django - Czy metody zapamiętywania modelu są leniwe?

Na przykład, w której linii w poniższym przykładzie kodu django trafi do bazy danych?

my_model = MyModel() 
my_model.name = 'Jeff Atwood' 
my_model.save() 
# Some code that is independent of my_model... 
model_id = model_instance.id 
print (model_id) 

Odpowiedz

7

Nie ma większego sensu mieć leniwego oszczędzania, prawda? Django's QuerySets są leniwi, metoda tego modelu jest inna niż w modelu save.

od źródła django:

django/db/models/base.py, wiersze 424-437:

def save(self, force_insert=False, force_update=False, using=None): 
    """ 
    Saves the current instance. Override this in a subclass if you want to 
    control the saving process. 

    The 'force_insert' and 'force_update' parameters can be used to insist 
    that the "save" must be an SQL insert or update (or equivalent for 
    non-SQL backends), respectively. Normally, they should not be set. 
    """ 
    if force_insert and force_update: 
     raise ValueError("Cannot force both insert and updating in \ 
      model saving.") 
    self.save_base(using=using, force_insert=force_insert, 
     force_update=force_update) 

save.alters_data = True 

Następnie save_base robi dźwiganie ciężarów (ten sam plik, wiersze 439-545):

... 
transaction.commit_unless_managed(using=using) 
... 

I w django/db/transaction.py, linie 167-178, znajdziesz:

def commit_unless_managed(using=None): 
    """ 
    Commits changes if the system is not in managed transaction mode. 
    """ 
    ... 

P.S. Wszystkie numery linii mają zastosowanie do wersji django (1, 3, 0, 'alpha', 0).

+1

Właściwie, w niektórych przypadkach preferowane byłyby leniwy zapis. Leniwe zapisy umożliwiłyby znacznie krótsze transakcje bez żadnego wysiłku po stronie programisty. Zobacz http://stackoverflow.com/questions/3215833/django-keeping-save-based-transactions-short – Jonathan

+0

Zgadzam się, dobra odpowiedź, ale tak, czasami ma to sens, aby mieć leniwą oszczędność. – Seth