[Answered ]-Django primary key in tests

2👍

So this is kind of dependent on several things with Django. The default test class they have you use will actually run each test in a transaction (https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.TestCase). This leads to your primary keys continuing to increment between classes.

There is also an argument that relying on the PK in a class can lead to bad assumptions…so you have a few choices

  1. Don’t rely on primary key value (good practice)
  2. Save the primary key after object creation and use that
  3. Use a different test case implementation that doesn’t do this to the tests. Consider (TransactionTestCase) which truncates between tests instead, and leads to more expected behavior (Although maybe not as fast…but I could never tell the difference really)

Leave a comment