2014-07-09 65 views
2

我正在使用http://www.django-rest-framework.org/如何在django rest框架中將多個變量傳遞給modelViewSet?

我有我想要傳遞兩個或多個變量的場景,我需要從數據庫中獲取數據。在下面的代碼中,只有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') 
+0

如何進行串行樣子?你能舉一個例子,說明這些字段缺失嗎?你的意思是一個ForeignKey? –

+0

@DenisCornehl使用序列化程序示例編輯了問題。 – theLeanDeveloper

回答

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) 

對於URL配置,它取決於找出你想如何發送你的變量(獲取,發佈或通過網址)。

希望這會有所幫助。

+0

我試了你的答案。我得到一個異常AttributeError:'WSGIRequest'對象沒有屬性'QUERY_DICT'相關的GET請求 – theLeanDeveloper

+0

Oups,我的壞。它是QUERY_PARAMS,請參見[here](http://www.django-rest-framework.org/api-guide/requests#query_params)。我沒有測試過這個確切的代碼,但我通常這樣做,所以我希望它現在可以工作。 – AdelaN

+0

謝謝AdelaN :) – theLeanDeveloper

4

以下是您如何使用最近的Django REST框架來實現它。

假設你的變量是在資源的URL像這樣:

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) 

那裏的'父母' queryset部分是你的父對象。當然,您可能需要稍微調整一下,但這個想法是封裝在kwargs中的。

該解決方案還可以爲您節省一些代碼,您只需通過子類化就可以使其成爲完整的ModelViewSet

希望有所幫助。

更多這裏:DRF Filtering against the URL

0

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'] 
相關問題