Skip to main content

django-pg-returning

A small library implementing PostgreSQL ability to return rows in DML statements for Django.
Link to PostgreSQL docs

Requirements

  • Python 2.7 or Python 3.3+
  • django >= 1.7
    Previous versions may also work, but haven't been tested.
  • pytz
  • six
  • typing
  • psycopg2
  • PostgreSQL 9.2+
    Previous versions may also work, but haven't been tested.

Installation

Install via pip:
pip install django-pg-returning
or via setup.py:
python setup.py install

Usage

Integration

The easiest way to integrate, is to inherit your model from UpdateReturningModel instead of django.db.models.Model. It already has redeclared Manager, supporting returning operations.

from django.db import models
from django_pg_returning import UpdateReturningModel

class MyModel(UpdateReturningModel):   
    field = models.IntegerField()

If you already have custom manager, you can implement get_queryset() method in it:

from django.db import models
from django_pg_returning import UpdateReturningQuerySet, UpdateReturningModel

class MyManager(models.Manager):
    def get_queryset(self):
        return UpdateReturningQuerySet(using=self.db, model=self.model)

class MyModel(UpdateReturningModel):
    objects = MyManager()

    field = models.IntegerField()

And if you have custom manager you can use a mixin:

from django.db import models
from django_pg_returning import UpdateReturningMixin, UpdateReturningModel

class MyQuerySet(models.QuerySet, UpdateReturningMixin):
    pass

class MyManager(models.Manager):
    def get_queryset(self):
        return MyQuerySet(using=self.db, model=self.model)

class MyModel(UpdateReturningModel):
    objects = MyManager()

    field = models.IntegerField()

Methods

QuerySet methods

After QuerySet mixin is integrated with your model, your QuerySet-s will have 2 additional methods:

# Any django queryset you like
qs = MyModel.objects.all()

# Update and return a ReturningQuerySet, described below
result = qs.update_returning(field=1)

# Delete data and return a ReturningQuerySet, described below
result = qs.delete_returning()

By default methods get all fields, fetched by the model. To limit fields returned, you can use standard QuerySet.only() and QuerySet.defer() methods.

Model methods

If model instance is created, basic save() method is called.
If model is updated, database record is updated, and saved fields are refreshed with database values. This may be useful, if you update fields with F() expressions. By default all fields are saved and refreshed. Use update_fields to specify concrete fields to save and refresh.

instance = MyModel.objects.create(pk=1, field=1)
instance.field = F('field') + 1

# Basic save method will not change field and you don't know, what value is in database
instance.save()
print(instance.field)
# Output: F('field') + Value(1)

# Library method gives ability to fetch updated result 
instance.save_returning()
print(instance.field)
# Output: 2

Important notes:

  1. If you don't fetch field, and then try to get it, library acts as django does - makes extra database query to fetch attribute deferred.
  2. These queries are not lazy, as well as basic QuerySet.update() and QuerySet.delete() methods.
  3. Primary key field is fetched not looking at limiting methods, as django needs it to form a QuerySet

ReturningQuerySet

The result of returning functions is django_pg_returning.ReturningQuerySet. It is based on django's RawQuerySet, but adds some extra methods to be used easier. The main difference is that ReturningQuerySet caches query results, while RawQuerySet executes query each time it is iterated. All ReturningQuerySet methods are not executed on database side, they are executed in python on cached result. The only way, ReturningQuerySet makes extra database query - is deferred field loading, described above. Implemented methods:

# UPDATE ... RETURNING query is executed here once. The result is cached.
result = MyModel.objects.all().update_returning(field=1)

# Get number of values fetched
print(result.count(), len(result))
# Output: 1, 1

# Index and slicing. Note that the order of result is not guaranteed by the database.
print(result[1], result[0:2])
# Output: MyModel(...), [MyModel(...), MyModel(...), MyModel(...)]

# Fetching values and values_list. Both methods use cache and return lists, not ValuesQuerySet like django does.
# values() method cakked without fields will return all fields, fetched in returning method.
# values_list() method called without fields will raise exception, as order or fields in result tuple is not obvious.

print(result.values())
# Output: [{'id': 1, 'field': 1}, {'id': 2, 'field': 2}]

print(result.values('field'))
# Output: [{'field': 1}, {'field': 2}]

print(result.values_list('field', flat=True))
# Output: [1, 2]

print(result.values_list('field', 'id', named=True))
# Output: [Row(field=1, id=1), Row(field=2, id=2)]

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-pg-returning-1.1.0.tar.gz (8.7 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

django_pg_returning-1.1.0-py3.6.egg (17.2 kB view details)

Uploaded Egg

django_pg_returning-1.1.0-py2.py3-none-any.whl (9.2 kB view details)

Uploaded Python 2Python 3

File details

Details for the file django-pg-returning-1.1.0.tar.gz.

File metadata

  • Download URL: django-pg-returning-1.1.0.tar.gz
  • Upload date:
  • Size: 8.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.5

File hashes

Hashes for django-pg-returning-1.1.0.tar.gz
Algorithm Hash digest
SHA256 92ceb3e9c2f49ec3dfac0a44319aa40c172f67924df719980e03c0b68d4a126e
MD5 e83019fe66743bfc66c3661a08b36e5a
BLAKE2b-256 be39c2c19d5c57ebf37759f2d980887dca88201a2bd68fac6021c2241a698734

See more details on using hashes here.

File details

Details for the file django_pg_returning-1.1.0-py3.6.egg.

File metadata

  • Download URL: django_pg_returning-1.1.0-py3.6.egg
  • Upload date:
  • Size: 17.2 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.6.7

File hashes

Hashes for django_pg_returning-1.1.0-py3.6.egg
Algorithm Hash digest
SHA256 1ef46c1343887f75ad5f1384a69e51adbefde5c38b83dea6400320b0e92831f9
MD5 e74ce5b23b680eb7cd17591e25c7c468
BLAKE2b-256 2ec7b05c82625805f8345498397c58d138ca79f7c8eef066cdf97113fdff2198

See more details on using hashes here.

File details

Details for the file django_pg_returning-1.1.0-py2.py3-none-any.whl.

File metadata

  • Download URL: django_pg_returning-1.1.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 9.2 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.5

File hashes

Hashes for django_pg_returning-1.1.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 f59851316a182e562671e70dfeaffba9838ba94092b1bad2260dc0be007493a5
MD5 9c9663ac3f1a7e7e5201848eefa4605b
BLAKE2b-256 1949fa8bd3afdc494bb4220b1e459ad95106eef1373a2875249624f70ee319a7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page