Django Unit Test – IDs of created objects

Question:

Sample models.py

models.py

class Food(models.Model):
    name = models.CharField(max_length=50, verbose_name='Food')

    def __str__(self):
        return self.name

Suppose that I have written unit test/s:

from django.test import TestCase
from myapp.models import Food

class TestWhateverFunctions(TestCase):
    """
    This class contains tests for whatever functions.
    """

    def setUp(self):
        """
        This method runs before the execution of each test case.
        """
        Food.objects.create(name='Pizza') # Will the created object have id of 1?
        Food.objects.create(name='Pasta') # Will the created object have id of 2?

    def test_if_food_is_pizza(self):
        """
        Test if the given food is pizza.
        """
        food = Food.objects.get(id=1)

        self.assertEqual(food.name, 'Pizza')

    def test_if_food_is_pasta(self):
        """
        Test if the given food is pasta.
        """
        food = Food.objects.get(id=2)

        self.assertEqual(food.name, 'Pasta')

I was wondering if it’s safe to assume that the id’s of the created objects in setUp() method will always start at id 1 and so on and so forth? If not, is there a specific reason why if the test database is always destroyed after running all tests?

Asked By: Paolo

||

Answers:

It is not safe to assume that the ids will always start at 1 and increment. They may have higher ids if other tests have run beforehand and created Food rows, and unit tests are not executed in any guaranteed order.

Save references to the model instances on your test setup:

class TestWhateverFunctions(TestCase):

    def setUp(self):
        self.food1 = Food.objects.create(name='Pizza')
        self.food2 = Food.objects.create(name='Pasta')
Answered By: wim

Thanks for the great example. For anyone as new as I am, I then used:

self.food1.id

as the primary key for testing a request and response of a URL.

Answered By: OptimisticToaster

use this to get the first object , no need to pass the id value

comment = Food.objects.get()

Answered By: LongDev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.