views:

45

answers:

1

I've got tables like the following (Django model definition, with a postgres database underlying it):

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=300)     
class Owner(models.Model):
    id = models.IntegerField()
    person = models.ForeignKey(Person) 

I use a Python script to set up my database from CSV files. The raw files list Owners with an integer id and an integer 'person' field, which maps to the integer in Person.id.

However, given that the 'person' column in Owner expects a Person object, how do I write a raw SQL string to insert value into Owner?

owner_id = 665
person_id = 330
sql_string = 'INSERT INTO owner (id, person) VALUES (' +
sql_string += owner_id + ', ' + ???? + ');'
A: 

You don't say why you need to do this in raw SQL. And I also don't understand why you're using structidx and person in the SQL when your PK field is called id - and the underlying column name for person is person_id. So your code should be:

sql_string = "INSERT INTO owner (`id`, `person_id`) VALUES (%s, %s)"
cursor = connection.cursor()
cursor.execute(sql_string, (665, 330))

Note that it's always good practice to use the Python db-api's quoting functionality, as I have here, to avoid SQL injection attacks.

Daniel Roseman