user823148
user823148

Reputation: 147

Django query not working

Here's the thing. I have a model called User and an attribute counter that counts the number of page access. So, if a user already exists, I have to query up the db and for that user only to increase in counter. Otherwise, create a new user. I have an annoying error in the get method. How can I surpass it?

if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            u = form.save()
            try:
                obj = User.objects.get(user=u.user)
                obj.counter += 1
                obj.ipaddress = request.META['REMOTE_ADDR']
                obj.save()
            except Statistic.DoesNotExist:
                ip = request.META['REMOTE_ADDR']
                obj = User(user=u.user, counter=1, ipaddress=ip)
                obj.save()
            return {'status': 'OK'}
        else:
            return {'errors': form.errors}
    return {'status': 'NOT OK. GET method'}
Here's the error
get() returned more than one User -- it returned 2! Lookup parameters were 

Upvotes: 0

Views: 2316

Answers (2)

Matt Williamson
Matt Williamson

Reputation: 40193

This means there are multiple users matching the query in your database. get should be used to fetch only one. It seems you are already coding for this but I think you are catching the wrong exception type. Try changing

except Statistic.DoesNotExist:

To

from django.core.exceptions import DoesNotExist
except DoesNotExist:

Upvotes: 0

dm03514
dm03514

Reputation: 55932

Django has amazing documentation on their QuerySet API. https://docs.djangoproject.com/en/dev/ref/models/querysets/

get only returns exactly 1 queryset. If no queryset is found, or more then 1 queryset is returned, an error is raised. To catch this particular error you have to specify except User.MultipleObjectsReturned,

Upvotes: 3

Related Questions