创建模型对象时出现无意义的值错误

2024-04-19 07:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我不太明白的错误问题。。 当我执行下面的代码时,我得到以下消息:

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)

Tags: namenoneevent类型ifobjectsisgroup
1条回答
网友
1楼 · 发布于 2024-04-19 07:18:58
ValueError: Cannot assign "[<Location: somename>]": "Event.location" must be a "Location" instance.

当它说[<Location: somename>]被传递时,括号表示它是一个列表。你知道吗

问题是l变量在代码中可能有不同的类型。你知道吗

这里是位置的查询集(列表兼容类型):

l=Location.objects.filter(name=location)

这里是一个位置:

l = Location(name=location)

您应该确保l在这两种情况下都包含一个位置,例如,使用以下else块:

    l=Location.objects.filter(name=location)
    if not l:
        l = Location(name=location)
        l.save()
    else:
        l = l[0]

当您试图获取一个location实例时,最好使用get()而不是filter()

try:
    l = Location.objects.get(name=location)
except Location.DoesNotExist:
    l = Location(name=location)
    l.save()

这就是get_or_create()方法的基本原理:

l, created = Location.objects.get_or_create(name=location)

使用get\u或\u create()时需要注意的一个常见陷阱是,它返回2个值。第一个是模型,第二个是布尔值,如果创建了对象,则为True,如果找到了对象,则为False。你知道吗

获取或创建文档:https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

相关问题 更多 >