Skip to content
This repository has been archived by the owner on Jan 27, 2023. It is now read-only.

Django queryset optimization support on multi db relation

License

Notifications You must be signed in to change notification settings

allieus/django-multi-db-relation

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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):
    pass

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']

then:

>>> 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

About

Django queryset optimization support on multi db relation

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%