Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django rest框架-没有这样的表_Python_Django_Mongodb_Django Rest Framework_Django Views - Fatal编程技术网

Python Django rest框架-没有这样的表

Python Django rest框架-没有这样的表,python,django,mongodb,django-rest-framework,django-views,Python,Django,Mongodb,Django Rest Framework,Django Views,我正试图在Django项目上创建一个API端点,以便从前端检索数据 我在django项目中使用了两个数据库,第一个是SQLite数据库,第二个是MongoDB数据库,我需要检索的数据在MongoDB上 这是我的模型: class tst(models.Model): _id = models.CharField(max_length=100) ticker = models.FloatField() def save(self): # ALL the signature

我正试图在Django项目上创建一个API端点,以便从前端检索数据

我在django项目中使用了两个数据库,第一个是SQLite数据库,第二个是MongoDB数据库,我需要检索的数据在MongoDB上

这是我的模型:

class tst(models.Model):
    _id = models.CharField(max_length=100)
    ticker = models.FloatField()

    def save(self): # ALL the signature

        super(Trade, self).save(using='dbtwo')
以下是我的看法:

class tstList(generics.ListCreateAPIView):
    queryset = tst.objects.all()
    serializer_class = tstSerializer
以及网址:

path('tst/', views.tstList.as_view()),
这里一切正常,但当我尝试从浏览器打开API时,我不断收到以下错误:

OperationalError at /tst/
no such table: main_tst
我认为这是因为它试图在第一个SQLite数据库上查找表
tst
,而不是在MongoDB数据库上查找它。有什么办法解决这个问题吗?我认为使用`dbtwo'添加
就可以了,但这不是正确的解决方案


感谢您的每一个建议

您需要为API视图定义在queryset中使用的数据库

class tstList(generics.ListCreateAPIView):
    queryset = tst.objects.using('dbtwo').all()
    serializer_class = tstSerializer
甚至比这更好的是,如果模型只使用另一个数据库,您可以这样做,这样您就不必每次都设置“using”

class MyRouter:

    def db_for_read(model, **hints):
        if model == tst:
            return 'dbtwo'

    def db_for_write(model, **hints):
        if model == tst:
            return 'dbtwo'

# In your settings
DATABASE_ROUTERS = ['path.to.MyRouter']

非常感谢。事实上,我刚刚了解了路由器,我将添加它们!再次感谢!你运行迁移了吗?