Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get() excepts MultipleObjectsReturned on a field marked unique

I have a field on a model that's marked unique:

uid = models.CharField(max_length=255, blank=False, null=False, unique=True)

I'm trying to use get() to get the one Profile that should match this uid:

UserProfile.objects.get(uid=fr_uid)

The problem is that this line raises a MultipleObjectsReturned exception for some users even though that field is marked unique:

Line: return self.get_query_set().get(*args, **kwargs)

Local variables:
clone   [<Profile: John Smith>, <Profile: John Smith>]
num     2

If I get the same profile from a shell, I only get one back:

Profile.objects.get(uid='abc1234')
<Profile: John Smith>

Now I understand that I should probably be handling a MultipleObjectsReturned exception anyway, but I cannot understand why I would ever get multiple objects returned on a field marked unique.

like image 913
Eric Conner Avatar asked Jan 29 '26 13:01

Eric Conner


1 Answers

Have you made any modifications to the manager? Or are you doing any sort of filtering on the queryset before calling get() on it? In particular, using Q objects for OR boolean searches can often result in the same object being returned multiple times. If that's the case, call distinct() on the queryset before get().

like image 189
Chris Pratt Avatar answered Feb 01 '26 01:02

Chris Pratt