How to get primary keys from pandas.to_sql insert
Asked Answered
A

0

6

I want to add some data to the database with pandas .to_sql command. Is there a way I can get the auto-generated primary-key of the inserted objects as I need it for creating foreign keys?

So far I did this:

Models:

from django.db import models
class Vertices(models.Model):
    x = models.FloatField()
    y = models.FloatField()
    z = models.FloatField()
class Face(models.Model):
    Points = models.ForeignKey(Vertices, on_delete=models.PROTECT,)

add points to db:

points.to_sql(Vertices._meta.db_table.lower(), con=engine, if_exists='append', index=False)

now I want to create a foreign key in the Face table to these points:

Face.objects.create(Points_id= ...)

Thank you very much!

Armorer answered 29/8, 2018 at 6:3 Comment(1)
Hi, does this solution help? #26770989 I've had the same question before, and I also just used the (inelegant) solution of returning the MAX(id), then adding it to the dataframe/other SQL table as a foreign key.Twentytwo

© 2022 - 2024 — McMap. All rights reserved.