django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題
get_or_create函數(shù)比較好用。
如果查詢到就返回,如果沒查詢到就向數(shù)據(jù)庫加入新的對象。
e.g.
size = Size.objects.get_or_create(sizeName=size_text)
注意:返回的是tuple,:(對象, 是否是創(chuàng)建的)
e.g. (size, created)
補充知識:Django update_or_create 注意事項
需求: model 修改數(shù)據(jù)庫數(shù)據(jù),數(shù)據(jù)存在則更新,不存在則保存
update_or_create 用法:
update_or_create(defaults=None, **kwargs)
kwargs: 來更新對象或創(chuàng)建一個新的對象。
defaults: 是由 (field, value) 對組成的字典,用于更新對象。
返回一個由 (object, created)組成的元組,
object: 是一個創(chuàng)建的或者是被更新的對象,
created: 是一個標示是否創(chuàng)建了新的對象的布爾值。
update_or_create: 方法通過給出的kwarg
try: obj = Person.objects.get(first_name=’John’, last_name=’Lennon’) for key, value in updated_values.iteritems(): setattr(obj, key, value) obj.save()except Person.DoesNotExist: updated_values.update({’first_name’: ’John’, ’last_name’: ’Lennon’}) obj = Person(**updated_values) obj.save()# 如果模型的字段數(shù)量較大的話,這種模式就變的非常不易用。上面的示例可以用 update_or_create() 重寫:obj, created = Person.objects.update_or_create( first_name=’John’, last_name=’Lennon’, defaults=updated_values)
以上這篇django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
