2010-07-09 29 views
7

Mô hình lưu() phương thức lười trong django?Django - Các mô hình save() có lười biếng không?

Ví dụ: tại dòng nào trong mẫu mã sau sẽ django nhấn vào cơ sở dữ liệu?

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) 

Trả lời

7

Sẽ không có ý nghĩa gì nếu bạn muốn tiết kiệm, phải không? Django's QuerySets là lười biếng, phương pháp của save của mô hình là không.

Từ nguồn django:

django/db/models/base.py, dòng 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 

Sau đó, save_base không những nâng nặng (cùng một tập tin, đường dây 439-545):

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

Và trong django/db/transaction.py, dòng 167–178, bạn sẽ tìm thấy:

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

T.B. Tất cả các số dòng áp dụng cho phiên bản django (1, 3, 0, 'alpha', 0).

+1

Thực tế, trong một số trường hợp, việc tiết kiệm sẽ thích hợp hơn. Việc tiết kiệm chi phí sẽ cho phép các giao dịch ngắn hơn nhiều mà không cần nỗ lực nào về phía lập trình viên. Xem http://stackoverflow.com/questions/3215833/django-keeping-save-based-transactions-short – Jonathan

+0

Đồng ý, câu trả lời hay, nhưng có đôi khi nó có ý nghĩa rất nhiều để có một lưu lười biếng. – Seth

Các vấn đề liên quan