How to insert into ForeignKey field using raw SQL?

I have tables like the following (defining a Django model with a postgres database):

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 am using a Python script to configure my database from CSV files. List of unprocessed files. Owners with an integer identifier and an integer field "person", which is mapped to an integer in Person.id.

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

owner_id = 665
person_id = 330
sql_string = 'INSERT INTO owner (id, person) VALUES (' +
sql_string += owner_id + ', ' + ???? + ');'
+3
source share
1 answer

, SQL. , structidx person SQL, PK id, person - person_id. :

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

, Python db-api, , SQL-.

+1

Source: https://habr.com/ru/post/1769887/


All Articles