2

How do you run a raw SQL query inside a Django unittest?

I find if I use a cursor, it seems to break the unittest's transaction so that any changes to the Sqlite database aren't reverted at the end of the unittest.

My unittest looks like:

class Tests(TestCase):

    def test_first(self):

        print('FIRST:', MyModel.objects.all().count())

        cursor = connection.cursor()
        try:
            cursor.execute('SELECT * FROM myapp_mymodel;')
            r = cursor.fetchone()
        finally:
            cursor.close()

        MyModel.objects.create(name='abc')

    def test_second(self):

        print('SECOND:', MyModel.objects.all().count())

and it currently outputs the unexpected:

FIRST: 0
SECOND: 1

and if I comment out the cursor code, then it outputs the correct result:

FIRST: 0
SECOND: 0

What black magic is going on here? Is connection.cursor not support inside Django's special unittest transaction?

Cerin
  • 60,957
  • 96
  • 316
  • 522
  • if there is an error you should post a full stacktrace. The accepted method of running raw queries in django is using the `raw()` method call. However even that is not needed in the test_case you have shown. A much simpler ORM query would work nicely here – e4c5 Dec 22 '16 at 05:28
  • Could you please show your imports as well? Thanks. – alecxe Dec 22 '16 at 05:57

0 Answers0