Django Rest Framework:从URL参数动态设置数据库 [英] Django Rest Framework: set database dynamically from URL parameter

查看:1094
本文介绍了Django Rest Framework:从URL参数动态设置数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找正确的方法:

I'm trying to find the right way to do this:

用户服务:

/api/<country>/users
/api/us/users

该服务应使用与URL中的国家/地区对应的数据库。

That service should use the database corresponding to the country in the URL.

settings.py:

settings.py:

DATABASES = {
'default': {},
'us': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'XXX_US', 
    'USER': 'US',
    'PASSWORD': 'XXX',
    'HOST': 'localhost',
    'PORT': '5432',
},
'es': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'XXX_ES', 
    'USER': 'ES',
    'PASSWORD': 'XXX',
    'HOST': 'localhost',
    'PORT': '5432',
}  }

要在ModelViewSet I中设置数据库到:

To set the database in the ModelViewSet I to this:

class UserViewSet(viewsets.ModelViewSet):

    model = User
    serializer_class = UserSerializer

    def get_queryset(self):
        country = self.kwargs['country']
        return User.objects.using(country).all()

当我尝试执行POST或PUT时,出现问题。我必须覆盖串行器的create()或save()方法吗?还有其他的方法吗?

The problem appears when I try to do a POST or PUT. Do I have to overwrite the create() or save() method of the serializer? Is there any other way to do this?

非常感谢!

推荐答案

我认为这种功能的最佳地方是 QuerySet ModelManager 。例如,DRF的默认序列化程序使用默认模型经理用于创建对象。不幸的是, QuerySet 没有办法轻松更改当前数据库( self.db ),具体取决于模型的字段,所以你必须覆盖所有相关的方法。

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.

class UserQuerySet(models.QuerySet):
    def create(self, **kwargs):
        obj = self.model(**kwargs)
        self._for_write = True
        obj.save(force_insert=True, using=kwargs.get('country'))
        return obj

class User(models.Model):
    objects = UserQuerySet.as_manager()

这篇关于Django Rest Framework:从URL参数动态设置数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆