Search code examples
djangodjango-rest-frameworkdjango-testingdjango-tests

Django queryset to string does not return the string in a test


I'm trying to write a unit test for this model:

ADMIN = 1
FULL_USER = 2
LIMITED_USER = 3

class Role(models.Model):
  """
  The class stores the model to store the different role which will be used to assign permissions
  to the users.
  """
  ROLE_CHOICES = (
        (ADMIN, 'admin'),
        (FULL_USER, 'full_user'),
        (LIMITED_USER, 'limited_user')
  )

  id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True)
  name = models.CharField('name', max_length=30)

  def __str__(self):
    """String for representing the Model object."""
    if self.name:
      return self.name
    return self.id

So I wrote this test:

from example.models import Role
from rest_framework.test import APITestCase

class RoleModel(APITestCase):

    fixtures = ["initial_data/role.json"]

    def test_get_admin_role(self):
        role = Role.objects.filter(id=1)
        self.assertEqual(str(role), 'admin')

But I'm not able to understand why it fails with this:

AssertionError: '<QuerySet [<Role: admin>]>' != 'admin'
- <QuerySet [<Role: admin>]>
+ admin

I have read similar questions on how to get the string of the queryset and it should be the one defined in __str__. but I don't know why it is surrounded by <QuerySet [<Role: HERE_IS_MY_STRING]> if I'm asking for the string representation of the object.


Solution

  • Your role is a QuerySet (a collection) of Roles. A collection can contain, zero, one, or more Roles. A collection is not the same as an object.

    You can obtain a Role object with .get(…) [Django-doc]:

    def test_get_admin_role(self):
        role = Role.objects.get(id=1)
        self.assertEqual(str(role), 'admin')

    Note that a __str__ object should always return a string, not an int for example. In the __str__ method, you thus should call str(…) on the .id:

    def __str__(self):
        """String for representing the Model object."""
        if self.name:
            return self.name
        return str(self.id)