1

I have the following pattern in my code:

cursor.execute("INSERT INTO main_catalog (1,'mark')")
conn.commit()

item = Catalog.objects.get(pk=1)
item.do_something()

However, I get an error saying that Catalog.DoesNotExist for id=1, even though I can see it in the database. How do I get the ORM to recognize this new value so I can then query it? (Note that I must use raw sql for certain reasons.)

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

As pointed out by @boxed, the accepted answer no longer works, however the close_old_connections() function he mentions worked for me. I.e.:

from django import db
db.close_old_connections()
Kenny Loveall
  • 519
  • 4
  • 16
-2

The following pattern works to reset the connection and get a 'fresh cursor':

from django import db

try:
    item = Catalog.objects.get(pk=1)
except Catalog.DoesNotExist:
    db.close_connection()
    item = Catalog.objects.get(pk=1)

This question may also be of use: Django multiprocessing and database connections.

Community
  • 1
  • 1
David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    This answer is now obsolete. There is no such function in django.db anymore. There is a close_old_connections() though which seems safe to call, maybe it does what we want here. – boxed Apr 20 '20 at 06:33