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!

MaxxiKing
  • 83
  • 6
  • Hi, does this solution help? https://stackoverflow.com/questions/26770489/how-to-get-autoincrement-values-for-a-column-after-uploading-a-pandas-dataframe 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. – Evan Aug 29 '18 at 13:42

0 Answers0