Django Raw SQL

I frequently use the Django TimeStampedModel. Recently I needed to generate some data to demo an app. Since the time stamps are important, I needed a way to make them different from now.

It was not clear how to alter TimeStampedModel behavior, so I decided to use Django’s raw SQL functionality. Should be pretty easy right? Kind of. Here is the example in the docs:

cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])

I wanted to select the record by “id”, maybe something like this?

cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %d", [3])

But that gives you:

django.db.utils.OperationalError: near "%": syntax error

Ah yes, I remember for days past that the Python SQL functionality uses “%s” for all placeholders, even integers. This works:

cursor.execute("UPDATE bar SET created = %s WHERE id = %s", [datetime.datetime.today(), 3])

Even the datetime is properly formatted. Nice!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s