get_or_create()
¶
get_or_create
(defaults=None, **kwargs)¶
A convenience method for looking up an object with the given kwargs
(may be empty if your model has defaults for all fields), creating one if necessary.
返回值是一个元组,元组里第一个元素是取回的对象,第二个对象是布尔值,前面的对象是否是新创建的(True表示是新创建的)。
Returns a tuple of (object, created)
, where object
is the retrieved or created object and created
is a boolean specifying whether a new object was created.
This is meant as a shortcut to boilerplatish code. For example:
try:
obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
obj.save()
This pattern gets quite unwieldy as the number of fields in a model goes up. The above example can be rewritten using get_or_create()
like so:
obj, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
https://docs.djangoproject.com/en/2.1/ref/models/querysets/#get-or-create
实际使用时遇到的一个怪问题,输入不同的数据,结果只能创建一条数据库记录,创建第二条是返回False,表示数据已存在:
import xlrd
from dbbackend.models import ZJcell, LngLat
class Cellinforeader:
"""读取excel的类"""
def __init__(self, path=r'C:\Users\Administrator\Desktop\嘉兴工参\圈定区域网内邻区关系(1).xlsx', sheetname='圈定小区'):
try:
self.workbook = xlrd.open_workbook(path)
self.sheet = self.workbook.sheet_by_name(sheetname)
except Exception:
print(Exception)
# 列名与列号字典,例如{'小区名称':2}
self.col_dict = {}
# sheet.ncols: Nominal number of columns in sheet.
for i in range(self.sheet.ncols):
self.col_dict[self.sheet.cell_value(0, i).strip()] = i
# 提取每行数据,导入小区数据库ZJcell中
def insertcells(self, cgi='CGI', cellname='小区名称', freq='频段', pci='PCID', lng='基站经度', lat='基站纬度',
azimuth='扇区方位角'):
for i in range(1, self.sheet.nrows):
print(i)
row = self.sheet.row_values(i)
print(row)
lnglat, createdornot1 = LngLat.objects.get_or_create({'lng': row[self.col_dict[lng]],
'lat': row[self.col_dict[lat]]})
cell, createdornot2 = ZJcell.objects.get_or_create({'cgi': row[self.col_dict[cgi]],
'cellname': row[self.col_dict[cellname]],
'freq': row[self.col_dict[freq]],
'pci': row[self.col_dict[pci]],
'lnglat': lnglat,
'azimuth': row[self.col_dict[azimuth]]})
仔细观察发现,我是用数据字典dict作为参数输入到 get_or_create()函数中,而官网的例子不是:
obj, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
仔细看,官网例子中没有加大括号{ },而只是按照普通带参数名的参数输入的。
我改成官网的形式后,问题就解决了。
我记得之前看过文档说dict的写法和普通写法通用,但是这里看有差异,再复习一下Python: 什么是*args和**kwargs:
挑关键的看:
def foo(*args, **kwargs):
print 'args = ', args
print 'kwargs = ', kwargs
print '---------------------------------------'
if __name__ == '__main__':
foo(1,2,3,4, a=1,b=2,c=3)
*args表示任何多个无名参数,它的输出是一个tuple;
args = (1, 2, 3, 4)
**kwargs表示关键字参数,它的输出是一个dict。
kwargs = {'a': 1, 'c': 3, 'b': 2}
他们的输入与普通参数的输入一样。
https://www.cnblogs.com/zhangzhuozheng/p/8053045.html