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)
When it says that
[<Location: somename>]was passed, the brackets means it’s a list.The problem is that the
lvariable can have different types in your code.Here it is a QuerySet (list-compatible type) of Location:
Here it is a location:
You should ensure that
lcontains a location in both cases, for example, with this else block:As you’re trying to get one location instance, you might as well use
get()instead offilter():That’s basically what does the
get_or_create()method: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