Django PostgreSQL Copy

2.8.0 · active · verified Sun Apr 12

django-postgres-copy is a Django package that facilitates fast and efficient bulk import and export of delimited data (like CSV files) to and from PostgreSQL databases, leveraging PostgreSQL's native `COPY` command. It is significantly faster than using Django's ORM for large datasets. The library is actively maintained, currently at version 2.8.0, and regularly updates to support recent Django and Python versions.

Warnings

Install

Imports

Quickstart

To use `django-postgres-copy`, first attach `CopyManager` to your Django model. You can then use the `from_csv()` method on your model's manager to import data from a CSV file, providing a path to the file and a dictionary mapping model fields to CSV headers. Similarly, `to_csv()` exports data. The library handles creating temporary tables and inserting data efficiently.

import os
from django.db import models
from postgres_copy import CopyManager

# Define a simple Django model with CopyManager
class Person(models.Model):
    name = models.CharField(max_length=500)
    number = models.IntegerField(null=True)
    date = models.DateField(null=True)

    objects = CopyManager()

    class Meta:
        app_label = 'myapp' # Replace with your app's name

# Example CSV content for 'data.csv'
# name,number,date
# ben,1,2024-01-01
# joe,2,2024-01-02
# jane,3,2024-01-03

# Create a dummy CSV file for the example (in a real scenario, this would be an existing file)
csv_content = "name,number,date\nben,1,2024-01-01\njoe,2,2024-01-02\njane,3,2024-01-03"
with open("data.csv", "w") as f:
    f.write(csv_content)

# --- Import data from CSV ---
# In a real Django setup, ensure your database connection is configured and migrations are run.
# Example: Person.objects.from_csv(
#    "./data.csv", 
#    dict(name="name", number="number", date="date") # Mapping model fields to CSV headers
# )

print("To import from CSV:")
print("Person.objects.from_csv('./data.csv', dict(name='name', number='number', date='date'))")

# --- Export data to CSV (assuming some data exists in the model) ---
# Example: Person.objects.to_csv("./export.csv")

print("\nTo export to CSV:")
print("Person.objects.to_csv('./export.csv')")

# Clean up dummy file
os.remove("data.csv")
# if os.path.exists("export.csv"): os.remove("export.csv") # Uncomment if testing export

view raw JSON →