Alec
Alec

Reputation: 43

Nonsensical ValueError when creating Model object

I have a problem with an Error I dont quite understand.. when i execute the code below, i get the following Message:

ValueError: Cannot assign "[<Location: somename>]": "Event.location" must be a "Location" instance.

It clearly states that "somename" is of the type Location, but complains that its the wrong type.. what should I do? Unfortunately the interpreter doesnt give me to many hints :(

    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)

Upvotes: 2

Views: 146

Answers (1)

jpic
jpic

Reputation: 33410

ValueError: Cannot assign "[<Location: somename>]": "Event.location" must be a "Location" instance.

When it says that [<Location: somename>] was passed, the brackets means it's a list.

The problem is that the l variable can have different types in your code.

Here it is a QuerySet (list-compatible type) of Location:

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

Here it is a location:

l = Location(name=location)

You should ensure that l contains a location in both cases, for example, with this else block:

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

As you're trying to get one location instance, you might as well use get() instead of filter():

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

That's basically what does the get_or_create() method:

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

A common pitfall you have to watch out for when using get_or_create(), is that it returns 2 values. The first being the model, the second being a boolean which is True if the object was created, and False if it was found.

Documentation for get_or_create: https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

Upvotes: 5

Related Questions