Django Unit Test Case: Getting MultipleObjectsReturned: get() returned more than one "Model" -- it returned 2!

314 views
Skip to first unread message

Jimish Parekh

unread,
May 22, 2014, 12:53:57 AM5/22/14
to django...@googlegroups.com
Hey Guys,
I am trying to write some unit test cases for web application I am working on. 

This unit test needs authentication so in my unit test I need to create a user and pass two extra parameters to get object of new model "UserProfile" which is using relation to django User class.

Here is my model User profile:
class UserProfile(models.Model):
user = models.ForeignKey(User,unique=True)
companyId = models.IntegerField(null=True,blank=True) # companyId of particular user
role = models.CharField(null=True,blank=True,max_length=50)

And here is my unit test case:
class IngredientAllTestCase(InitialSetUp,TestCase):
def setUp(self):
Ingredient.objects.create(name='sugar3',status='published',description='no need',config='null')
self.user=User(username='jimish')
password = 'password'
self.user.set_password(password)
self.companyId = '227329282382'
self.role = 'QA Manager'
self.user.save()
UserProfileObj = UserProfile.objects.create(user=self.user,companyId=self.companyId,role=self.role)
self.client = Client()
self.factory = RequestFactory()
self.client.login(username=self.user.username, password=password)

def test_IngredientAll(self):
url = reverse('lib:ingredient-all')
response = self.client.get(url)
self.assertEqual(response.status_code,status.HTTP_200_OK)

While running test case, I am getting error:
MultipleObjectsReturned: get() returned more than one UserProfile -- it returned 2! Lookup parameters were {'user': u'537d804b041b00108380b861'}

So, please help me. Any answers would be helpful and I would like to thank you guys in advance.

Jimish Parekh

unread,
May 23, 2014, 12:41:13 AM5/23/14
to django...@googlegroups.com
Bug is resolved.
I was trying to create another UserProfile object while there was already one created when I created User class object...
I just needed to fire a get query to access UserProfile of that User class object and save those two attributes into that object.
Reply all
Reply to author
Forward
0 new messages