Login

Forcing DB on relationship manager with multiple database project

Author:
ryananguiano
Posted:
November 6, 2014
Language:
Python
Version:
1.5
Score:
0 (after 0 ratings)

I have a master/slave SQL setup and sometimes I need to access the data immediately after write, but the data has not yet propagated to the slave yet.

This forces me to require .using('default') every time that relationship is accessed. Ex: self.books.using('default').all().delete()

Setting objects = ForceDefaultDBManager() on the related object removes this requirement throughout your code. This now does the same as the last example: self.books.all().delete()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    from django.db import models
    
    class ForceDefaultDBManager(models.Manager):
        db = 'default'  # Put your db alias here
        use_for_related_fields = True
    
        def using(self, *args, **kwargs):
            return self.get_query_set().using(self.db)
    
    class Library(models.Model):
        name = models.CharField()
    
    class Book(models.Model):
        library = models.ForeignKey(Library, related_name='books')
        name = models.CharField()
    
        objects = ForceDefaultDBManager()

More like this

  1. get_object_or_none by azwdevops 3 months, 3 weeks ago
  2. Mask sensitive data from logger by agusmakmun 5 months, 2 weeks ago
  3. Template tag - list punctuation for a list of items by shapiromatron 1 year, 7 months ago
  4. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 8 months ago
  5. Serializer factory with Django Rest Framework by julio 2 years, 2 months ago

Comments

Please login first before commenting.