开发者

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 an开发者_如何学编程noying 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 


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,


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:
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜