I am trying to insert data into a Pandas DataFrame into an existing Django, Agency model that uses the SQLite backend. However, after answering How to write a Pandas Dataframe for a Django Model and Saving a Pandas DataFrame with a Django Model , the whole SQLite table is replaced and the Django code is split. In particular, this is an automatic generated id column in Django, which is replaced by index , which causes errors when rendering templates ( no such column: agency.id ).
Here is the code and the result of using Pandas to_sql in the SQLite table, Agency .
In models.py :
class Agency(models.Model): name = models.CharField(max_length=128)
In myapp/management/commands/populate.py :
class Command(BaseCommand): def handle(self, *args, **options): # Open ModelConnection from django.conf import settings database_name = settings.DATABASES['default']['NAME'] database_url = 'sqlite:///{}'.format(database_name) engine = create_engine(database_url, echo=False) # Insert data data agencies = pd.DataFrame({"name": ["Agency 1", "Agency 2", "Agency 3"]}) agencies.to_sql("agency", con=engine, if_exists="replace")
The call to ' python manage.py populate ' successfully adds three agencies to the table:
index name 0 Agency 1 1 Agency 2 2 Agency 3
However, this changed the DDL of the table:
CREATE TABLE "agency" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(128) NOT NULL)
in
CREATE TABLE agency ( "index" BIGINT, name TEXT ); CREATE INDEX ix_agency_index ON agency ("index")
How can I add a DataFrame to a Django-driven model and keep the Django ORG intact?