Reputation: 1297
I'm trying to create an API endpoint on my Django project to retrieve data from my frontend.
I'm using two DBs on my django project, the first one is a SQLite DB, the second one is a MongoDB database, the data i need to retrieve is on MongoDB.
Here is my model:
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')
Here is my view:
class tstList(generics.ListCreateAPIView):
queryset = tst.objects.all()
serializer_class = tstSerializer
And the url:
path('tst/', views.tstList.as_view()),
Everything is alright here but when i try to open the API from my browser, i keep getting the following error:
OperationalError at /tst/
no such table: main_tst
I think this happens because it tries to look for the table tst
on the first SQLite database, instead of looking for it on the MongoDB one. Is there any way to solve this? I thought that adding using='dbtwo'
would do it, but it's not the right solution.
Every advice is appreciated!
Upvotes: 0
Views: 397
Reputation: 32294
You need to define the database that you are using in the queryset for your API view
class tstList(generics.ListCreateAPIView):
queryset = tst.objects.using('dbtwo').all()
serializer_class = tstSerializer
Even better than this, if the model will only ever use the other database, you can set up a router so that you do not have to set "using" every time
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']
Upvotes: 1