Skip to main content

Django query optimization supports for multi db relations.

Project description

# django-multi-db-relation

> Queryset optimization supports for multi database spanning relations between Django models.

## Requirements

- Python (>= 3.5)
- Django (>= 1.10)

## Installation

pip install django-multi-db-relation

## Usage

For models

class ModelA(models.Model):
name = models.CharField(max_length=10)

class ModelB(models.Model):
a = models.ForeignKey(ModelA, on_delete=models.DO_NOTHING)

class ModelC(models.Model):
b = models.ForeignKey(ModelB, on_delete=models.DO_NOTHING, db_constraint=False)

suppose that `ModelA` and `ModelB` is routed to `db1` and `ModelC` to `db2`.

We **cannot** run a queryset with `select_related()`.

>>> ModelC.objects.select_related('b') # Table not found

In this case, modify `ModelC` like:

from multi_db_relation.mixins import ExternalDbQuerySetMixin

class ModelCQuerySet(ExternalDbQuerySetMixin, models.QuerySet):

class ModelC(models.Model):
b = models.ForeignKey(ModelB, on_delete=models.DO_NOTHING, db_constraint=False)

objects = models.Manager.from_queryset(queryset_class=ModelCQuerySet)()

class Meta:
external_db_fields = ['b']


>>> ModelC.objects.select_related('b') # Number of queries is optimized from O(n) to O(1)
>>> ModelC.objects.select_related('b__a') # Also works well

## License


Project details

Release history Release notifications

This version


Download files

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

Files for django-multi-db-relation, version 0.1
Filename, size & hash File type Python version Upload date
django_multi_db_relation-0.1-py3-none-any.whl (4.7 kB) View hashes Wheel py3

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page