2016-04-21 100 views
0
批量更新(具有唯一值)

比方說,我有http://stardict.sourceforge.net/Dictionaries.php下載與電子郵件和生日列表:途徑在Django

p = [\ 
    {'email': '[email protected]', 'birthday': '1990-01-01'}, 
    {'email': '[email protected]', 'birthday': '1980-02-05'}, 
    #...etc 
] 

我想更新數據庫的People對象。原始SQL通常會擁有多達查詢,len(p),所以這讓我想到這樣做的:我沒有經歷過

from django.db import IntegrityError, transaction 
for person in p: 
    try: 
     with transaction.atomic(): 
      People.objects.filter(email=person['email']).update(birthday=person['birthday']) 
    except IntegrityError: 
     #handle the exception 

足夠的Django知道這是很好的做法,但。什麼是表達我想要做的最Python的方式?

+0

所有這些電子郵件ID是否已經存在於數據庫中?在'People'表中可以有多個條目用於相同的電子郵件ID? – AKS

+0

我想這是檢查更新的好習慣,但不應該有重複;這已經在插入驗證。在上面的代碼中,任何具有相同電子郵件的「人物」都會得到相同的生日。 – Escher

+0

爲了更好的代碼,你可以在transaction.atomic():'for for循環之外寫'。 – AKS

回答

0

當您過濾和更新時,相同的更新將應用於所有過濾的條目。 Django不提供批量更新操作,您可以在其中更新不同條目上的不同值。

你可以讓你的代碼通過包含transaction.atomic()塊內的for循環,而不必爲循環中的每個條目的原子塊好:

with transaction.atomic(): 
    for person in p: 
     try:    
      People.objects.filter(email=person['email']).update(birthday=person['birthday']) 
     except IntegrityError: 
      #handle the exception 
0

有一個庫:django-bulk-update

people = Person.objects.all() 
for person in people: 
    person.name = random.choice(random_names) 

bulk_update(people, update_fields=['name']) 
# or 
Person.objects.bulk_update(people, update_fields=['name'])