Skip to content

Commit

Permalink
Add example requested in palewire#168.
Browse files Browse the repository at this point in the history
  • Loading branch information
geoffrey-eisenbarth committed Jun 15, 2023
1 parent 15392f1 commit 472cdad
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,39 @@ Now you can run that subclass directly rather than via a manager. The only diffe
# Then save it.
c.save()
For example, if you wish to return a QuerySet of the models imported into the database, you could do the following:

.. code-block:: python
from django.db import models
from postgres_copy import CopyMapping, CopyQuerySet
class ResultsCopyMapping(CopyMapping):
def insert_suffix(self) -> str:
"""Add `RETURNING` sql clause to get newly created/updated ids."""
suffix = super().insert_suffix()
suffix = suffix.split(';')[0] + ' RETURNING id;'
return suffix
def post_insert(self, cursor) -> None:
"""Extend to store results from `RETURNING` clause."""
self.obj_ids = [r[0] for r in cursor.fetchall()]
class ResultsCopyQuerySet(CopyQuerySet):
def from_csv(self, csv_path_or_obj, mapping=None, **kwargs):
mapping = ResultsCopyMapping(self.model, csv_path_or_obj, mapping=None, **kwargs)
count = mapping.save(silent=True)
objs = self.model.objects.filter(id__in=mapping.obj_ids)
return objs, count
class Person(models.Model):
name = models.CharField(max_length=500)
number = models.IntegerField()
source_csv = models.CharField(max_length=500)
objects = ResultsCopyQuerySet.as_manager()
Export options
==============
Expand Down

0 comments on commit 472cdad

Please sign in to comment.