How to Use django-adaptors

django-adaptors is a Django application that provides tools for importing and exporting data to and from Django models using adapters. It simplifies the process of handling various data formats like CSV, XML, and more. This guide will walk you through installing django-adaptors and demonstrate how to use it effectively in your Django projects.

Installation

To install django-adaptors, you can use pip:

pip install django-adaptors
    

Add 'django_adaptors' to your INSTALLED_APPS in your project’s settings.py:

# settings.py

    INSTALLED_APPS = [
        # ...
        'django_adaptors',
        # ...
    ]
    

Importing Data from CSV

Let’s say you have a CSV file with data that you want to import into your Django model. Here’s how you can do it using django-adaptors.

Define Your Model

First, define your Django model. For example, a simple Person model:

See also  How to reset secret key in Django

# models.py

    from django.db import models

    class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField(unique=True)

        def __str__(self):
            return f"{self.first_name} {self.last_name}"
    

Create an Adapter

Next, create a CSV adapter that maps the CSV fields to your model fields:

# adapters.py

    from django_adaptors import models
    from .models import Person

    class PersonCSVAdapter(models.CsvDbModel):
        class Meta:
            dbModel = Person
            delimiter = ';'
            has_header = True
            mapping = {
                'first_name': 'FirstName',
                'last_name': 'LastName',
                'email': 'Email',
            }
    

In the adapter:

  • dbModel: The Django model to which data will be imported.
  • delimiter: The delimiter used in the CSV file (e.g., comma, semicolon).
  • has_header: Indicates if the CSV file has a header row.
  • mapping: A dictionary mapping model fields to CSV column headers.

Import Data

Now, you can import data from a CSV file into your model:

See also  How does Django connect to external database?

# import_data.py

    from .adapters import PersonCSVAdapter

    # Read CSV data from a file
    with open('people.csv', 'r') as csv_file:
        content = csv_file.read()

    # Import data using the adapter
    result = PersonCSVAdapter.import_from_string(content)

    # Check for errors
    if result.errors:
        print("Errors occurred during import:")
        for error in result.errors:
            print(error)
    else:
        print(f"Successfully imported {len(result.cleaned_objects)} records.")
    

Exporting Data to CSV

You can also export data from your Django models to a CSV file using django-adaptors.

Create an Export Adapter

Define a CSV adapter for exporting data:

# adapters.py (add to existing code)

    class PersonCSVExporter(models.CsvModel):
        first_name = models.CharField()
        last_name = models.CharField()
        email = models.EmailField()

        class Meta:
            delimiter = ';'
            has_header = True
    

Export Data

Use the exporter to write data to a CSV file:

# export_data.py

    from .adapters import PersonCSVExporter
    from .models import Person

    # Query the data you want to export
    people = Person.objects.all()

    # Convert queryset to CSV string
    csv_data = PersonCSVExporter.export_csv(people)

    # Write to a CSV file
    with open('exported_people.csv', 'w') as csv_file:
        csv_file.write(csv_data)
    

Handling Import Errors

django-adaptors provides mechanisms to handle errors during data import. When calling import_from_string(), it returns a result object containing:

See also  How to set timezone in Django?

  • errors: A list of errors encountered during import.
  • cleaned_objects: A list of successfully imported objects.

You can use this information to log errors or take corrective actions.

Importing Data from Other Formats

While this guide focuses on CSV files, django-adaptors also supports other data formats like XML. You can create adapters similar to the CSV adapter for different formats by extending the appropriate classes provided by django-adaptors.

Additional Resources