Skip to content
Advertisement

Querying the database in a Django unit test

I am creating a web application which has a POST endpoint, that does two things:

  1. Saves the POSTed data (a university review) in the database.
  2. Redirects the user to an overview page.

Here is the code for it:

JavaScript

I haven’t yet implemented passing the user data to the endpoint, and that’s why I’m saving everything under the user with pk=1.

My test is as follows:

JavaScript

The result is this:

JavaScript

Why is this happening? I know the user I’m creating has a pk=1, as when I actually print it during the test it’s 1.

Advertisement

Answer

pk is defined by the database. Something could make it not equal to 1 in your test.

Try this in your setUp method

JavaScript
Advertisement