我有一个我不太明白的错误问题。。 当我执行下面的代码时,我得到以下消息:
ValueError: Cannot assign "[<Location: somename>]": "Event.location" must be a "Location" instance.
它明确指出“somename”是Location类型,但抱怨它的类型不对。。我该怎么办?不幸的是,翻译没有给我很多提示:(
if location is not None:
location = location.group(1)
l=Location.objects.filter(name=location)
if not l:
l = Location(name=location)
l.save()
if price is not None:
price = price.group(1)
if starttime is not None:
starttime = extract_time_from_string(starttime.group(1))
if name is not None:
name = name.group(1)
if edate is not None and name is not None and l is not None:
if not Event.objects.filter(name = name, eventdate=edate,
location = l):
e= Event(location = l, name = name,
eventdate=edate, starttime=starttime,
price=price)
当它说
[<Location: somename>]
被传递时,括号表示它是一个列表。你知道吗问题是
l
变量在代码中可能有不同的类型。你知道吗这里是位置的查询集(列表兼容类型):
这里是一个位置:
您应该确保
l
在这两种情况下都包含一个位置,例如,使用以下else块:当您试图获取一个location实例时,最好使用
get()
而不是filter()
:这就是
get_or_create()
方法的基本原理:使用get\u或\u create()时需要注意的一个常见陷阱是,它返回2个值。第一个是模型,第二个是布尔值,如果创建了对象,则为True,如果找到了对象,则为False。你知道吗
获取或创建文档:https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
相关问题 更多 >
编程相关推荐