0

I have a simple model that have a __str__ method that returns a string as expected, but when testing the __str__ method it returns a Queryset and the test fails. Why this happens? I am already calling the method using str() instead of __str__() as this other post suggested

class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField()

    def __str__(self):
        return self.user.username

In the shell it returns the username from the corresponding User object as a string, as expected:

author = Author.objects.get(pk=1)
str(author)
'edumats'

But when testing the __str__ method of the model, the test fails, as the method returns a Queryset:

The test:

def test_author_methods(self):
        author1 = Author.objects.filter(user__username='Test User')
        self.assertEqual(str(author1), 'Test User')

The error from the test:

FAIL: test_author_methods (posts.test_models.PostTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/edumats/Projects/blog/blog/posts/test_models.py", line 37, in test_author_methods
    self.assertEqual(str(author1), 'Test User')
AssertionError: '<QuerySet [<Author: Test User>]>' != 'Test User'
- <QuerySet [<Author: Test User>]>
+ Test User
Eduardo Matsuoka
  • 566
  • 6
  • 18
  • 3
    `.get()` method returns the object whereas the `.filter()` method returns a queryset. So to fetch the username of first user you could do the following : `author1 = Author.objects.filter(user__username='Test User').first()` – Ajay Lingayat Jan 16 '21 at 19:50
  • Thank you @AjayLingayat I forgot that .get() and .filter() return differently. Using first() solved the issue. – Eduardo Matsuoka Jan 16 '21 at 20:06

0 Answers0