如何在django rest框架中将多个变量传递给modelViewSet?

时间:2014-07-09 15:37:08

标签: python django rest django-rest-framework

我正在使用http://www.django-rest-framework.org/

我有这样的场景,我想根据我需要从数据库中获取数据来传递两个或更多变量。在下面的代码中,只有pk是我想用数据库中的其他两个字段替换的。

另外请建议我如何编写我的urlconfig相同。

Views.py

class ExampleViewSet(viewsets.ReadOnlyModelViewSet):
    model = myTable
    def list(self, request):
        queryset = myTable.objects.all()
        serializer = mySerializer(queryset, many=True)
        return Response(serializer.data)
    def retrieve(self, request, pk=None):
        queryset = myTable.objects.all()
        s = get_object_or_404(queryset, pk=pk)
        serializer = mySerializer(s)
        return Response(serializer.data)

Serializer.py

class Serializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = myTable
        fields = ('attr1', 'attr2', 'attr3')

3 个答案:

答案 0 :(得分:7)

以下是使用最近的Django REST Framework的方法。

假设您的变量位于资源网址中,如下所示:

GET /parent/:id/child/
GET /parent/:id/child/:id/

然后:

urls.py:

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'parent/(?P<parent_id>.+)/child', views.ExampleViewSet)
urlpatterns = router.urls

views.py:

class ExampleViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = Serializer

    def get_queryset(self):
        parent = self.kwargs['parent']
        return myTable.objects.filter(parent=parent)

父母在哪里&#39;在queryset部分中是您的父对象。当然,你可能需要稍微调整一下,但这个想法是封装在kwargs中。

此解决方案还可以为您节省一些代码,只需通过子类化即可将其变为完整的ModelViewSet

希望有所帮助。

更多信息:DRF Filtering against the URL

答案 1 :(得分:4)

以下是如何实现所需内容的示例:

class ExampleViewSet(viewsets.ReadOnlyModelViewSet):
# This code saves you from repeating yourself
queryset = myTable.objects.all()
serializer_class = mySerializer

def list(self, request, *args, **kwargs):
    # Get your variables from request
    var1 = request.QUERY_DICT.get('var1_name', None) # for GET requests
    var2 = request.DATA.get('var2_name', None) # for POST requests
    if var1 is not None:
        # Get your data according to the variable var1
        data = self.get_queryset().filter(var1)
        serialized_data = self.get_serializer(data, many=True)
        return Response(serialized_data.data)

    if var2 is not None:
        # Do as you need for var2
        return Response(...)

    # Default behaviour : call parent
    return super(ExampleViewSet, self).list(request, *args, **kwargs)

def retrieve(self, request, *args, **kwargs):
    # Same for retrieve
    # 1. get your variable xyz from the request
    # 2. Get your object based on your variable's value
    s = myTable.objects.get(varX=xyz)
    # 3. Serialize it and send it as a response
    serialized_data = self.get_serializer(s)
    return Response(serialized_data.data)
    # 4. Don't forget to treat the case when your variable is None (call parent method)

对于 urlconf ,这取决于您希望如何发送变量(获取,发布或通过网址)。

希望这有帮助。

答案 2 :(得分:-1)

urls.py

  url( 
        regex=r'^teach/(?P<pk>\d+?)/(?P<pk1>\d+?)/$', 
        view=teach_update.as_view(), 
        name='teach' 
   )

模板

<td><a href="/teach/{{tid}}/{{i.id}}"><button type="button" class="btn       
btn-warning">Update</button></a></td>

Views.py

class teach_update(view):
     def get(self,request,**kwargs):
        dist=self.kwargs['pk']
        ddd=self.kwargs['pk1']