开发者

How to insert into a ForeignKey field using raw SQL?

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

c开发者_如何学运维lass 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 + ', ' + ???? + ');'


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜