1

Currently, when referencing any foreign keys, (many to many, one to many) DRF seems to grab the information from the default (auth) database, so I get errors saying "relation does not exist" because there is not a table that exists within the auth db for what I am trying to get. I would like it to choose from the same database as request. Is there any way to get request (or self) inside of a serializer so I can choose the db from that? I believe it is possible on create/update using

def to_internal_value(self, data):
    request = self.context.get('request')

But this is only called on create/update, is there a way to do so when just listing the values? My initial query (from viewset) selects from the correct db as I can choose it via request, but when it goes through the serializer it tries to get foreign keys from default (auth) db. There must be some way to specify the database and not have it use default right?

user3610386
  • 109
  • 11
  • Are you trying to implement/use the [**Django DB Routing**](https://docs.djangoproject.com/en/2.1/topics/db/multi-db/) using DRF?? – JPG Mar 12 '19 at 15:50
  • I'm just trying to stop the serializer from using the default db (and use the same db as the initial query was done with), not sure whether it's DRF or Django that's the issue (Sorry, am new to Django/DRF) – user3610386 Mar 12 '19 at 16:00
  • Actually, I don't understand what you mean by ***default DB*** – JPG Mar 12 '19 at 16:02
  • We have 2 databases, one is auth, one is lets say walmart, for some reason all foreign key calls try to get information from the auth database by default (which is why I called it default db) and I was wondering if there was a way to stop this from happening – user3610386 Mar 12 '19 at 16:17
  • 1
    DB or DB Table? – JPG Mar 12 '19 at 16:41
  • DB (If I understand the difference), for any field I choose (that's a relation) it uses the auth database and tries to get the table from there, whereas my view will use the request db as wanted – user3610386 Mar 12 '19 at 16:56
  • 2
    The DB I believe is not specified in the request but in the model level. As JPG already mentioned above, there's a Django configuration for that. Ideally, DRF should be unaware of that and the models should specify which database they are to connect to. Check this page for more details https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#topics-db-multi-db-routing – Ken4scholars Mar 12 '19 at 21:47

1 Answers1

0

You might might be able to do it at the view level, using get_queryset

class YourModelDRFGetView(generics.ListAPIView):
    serializer_class = YourModelDRFViewSerializer

    def get_queryset(self):
        return YourModel.objects.using('your_read_replica').all()

Where your_read_replica is defined in settings.py:

replica_database_url = os.environ.get("DATABASE_REPLICA_URL") or database_url
DATABASES["your_read_replica"] = dj_database_url.parse(replica_database_url)
jmunsch
  • 22,771
  • 11
  • 93
  • 114