Django Rest Framework: Set Database Dynamically From Url Parameter
I'm trying to find the right way to do this: Users service: /api//users /api/us/users That service should use the database corresponding to the country in the URL.
Solution 1:
I think the best place for such functionality is a QuerySet
or a ModelManager. For example, the DRF's default serializer uses the default model's manager for creating objects. Unfortunately, the QuerySet
doesn't have a way to easily change the current database (self.db
) depending on the models' fields, so you'll have to override all the relevant methods.
classUserQuerySet(models.QuerySet):
defcreate(self, **kwargs):
obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=kwargs.get('country'))
return obj
classUser(models.Model):
objects = UserQuerySet.as_manager()
Solution 2:
Thank you Alex! You answer help me a lot. To fully solve the problem I have to do this:
views.py
classUserViewSet(viewsets.ModelViewSet):
model = User
serializer_class = UserSerializer
defperform_create(self, serializer):
serializer.validated_data['country'] = self.kwargs.get('country')
serializer.create(serializer.validated_data)
And then in the models.py:
classUserQuerySet(models.QuerySet):
defcreate(self, **kwargs):
country = kwargs.get('country') #Get the country
kwargs.pop('country') #Pop the country from kwargs
obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=country)
return obj
classUser(models.Model):
objects = UserQuerySet.as_manager()
id = models.AutoField(primary_key=True,db_column='user_id')
name = models.CharField(max_length=40)
classMeta:
managed = True
db_table = Constants().USER
And the problem is solved! Thank you a lot.
Post a Comment for "Django Rest Framework: Set Database Dynamically From Url Parameter"