Shubham Gupta
Shubham Gupta

Reputation: 159

Using Sql and MongoDb with Django rest framework for apis

I am new to django and it to use sql db as default but also connect it to mongoldb. In my models.py i

from mongoengine import Document, EmbeddedDocument, fields

class ToolInput(EmbeddedDocument):
    name = fields.StringField(required=True)
    value = fields.DynamicField(required=True)

class Tool(Document):
    label = fields.StringField(required=True)
    description = fields.StringField(required=True, null=True)
    inputs = fields.ListField(fields.EmbeddedDocumentField(ToolInput))

In my serializers.py I have :-

from .models import Tool
from rest_framework_mongoengine import serializers as mongoSerializers
from .models import Tool

class ToolSerializer(mongoSerializers.DocumentSerializer):
    class Meta:
    model = Tool
    fields = '__all__'

In my api.py I have :-

from .serializers import ListSerializer, CardSerializer, ToolSerializer
from rest_framework.generics import ListAPIView
from rest_framework_mongoengine import viewsets as mongoViewsets
from .models import List, Card, Tool

class ToolApi(mongoViewsets.ModelViewSet):
    #lookup_field = 'id'
    queryset = Tool.objects.all()
    serializer_class = ToolSerializer

In my urls.py I have :-

from django.conf.urls import include, url
from .api importToolApi

urlpatterns = [
    url(r'Tool', ToolApi.as_view({'get': 'Tool'})),
]

When I hit this api, error says :- 'ToolApi' object has no attribute 'Tool'

Earlier I was using ListAPIView class from rest_framework.generics to create api to acess data from sql. Is the error because I have used ModelViewSet for ToolApi?

PS - Please refer me to some git project using both mongodb and sql

Upvotes: 0

Views: 857

Answers (1)

Boris Burkov
Boris Burkov

Reputation: 14436

Sorry for late response, Shubham.

I think, the problem is that you shouldn't be using {'get': 'Tool'} in:

urlpatterns = [
    url(r'Tool', ToolApi.as_view({'get': 'Tool'})),
]

Instead you should use something like:

urlpatterns = [
    url(r'Tool', ToolApi.as_view({'get': 'list'})),
]

or

urlpatterns = [
    url(r'Tool', ToolApi.as_view({'get': 'retrieve'})),
]

As for the example repo, I'm afraid, I can't offer anything better than: https://github.com/BurkovBA/django-rest-framework-mongoengine-example/stargazers.

Upvotes: 1

Related Questions