久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題

瀏覽:143日期:2024-10-06 09:05:27

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)。

標簽: Django
相關文章:
主站蜘蛛池模板: 汝阳县| 辽阳县| 义乌市| 黔江区| 淄博市| 阳高县| 阿克陶县| 铜陵市| 永清县| 安龙县| 灵山县| 固镇县| 溧阳市| 华坪县| 青冈县| 开阳县| 汉寿县| 讷河市| 周口市| 丰宁| 治县。| 大竹县| 花莲县| 和田县| 阿尔山市| 宝山区| 界首市| 兰西县| 廊坊市| 诸城市| 邹城市| 长葛市| 乡城县| 大名县| 肃南| 沧源| 塔城市| 平远县| 郓城县| 太原市| 公安县|