簡體   English   中英

如何使用rest_framework和Django獲取多個對象的響應

[英]How to get a response of multiple objects using rest_framework and Django

我是Django框架和Django REST框架的新手,但我得到了基本的設置和實現。 當我為單個對象調用域時,它就像一個魅力,例如http://mydomain.com/location/1 (其中1是主鍵)。 這給了我JSON響應,如:

{"id": 1, "location": "Berlin", "country": 2}

..和http://mydomain.com/country/2響應如下:

{"id": 2, "country": "Germany"}

我需要的是:現在我需要獲得多個位置,例如在調用域http://mydomain.com/all_locations/時 我希望得到如下回復:

[
  {"id": 1, "location": "Berlin", "country": 2},
  {"id": 2, "location": "New York", "country": 4},
  {"id": 3, "location": "Barcelona", "country": 5},
  {"id": 4, "location": "Moscow", "country": 7}
]

這是可選的:第二步,當我打電話給http://mydomain.com/mix_all_locations_countries/時 ,我希望在一個響應中有多個國家和地點,例如:

[
  {"locations":
    {"id": 1, "location": "Berlin", "country": 2},
    {"id": 2, "location": "New York", "country": 4},
    {"id": 3, "location": "Barcelona", "country": 5},
    {"id": 4, "location": "Moscow", "country": 7}
  },
  {"countries":
    {"id": 1, "country": "Brazil"}
    {"id": 2, "country": "Germany"},
    {"id": 3, "country": "Portugual"}
    {"id": 4, "country": "USA"},
    {"id": 5, "country": "Spain"},
    {"id": 6, "country": "Italy"}
    {"id": 7, "country": "Russia"}
  }
]

這是我到目前為止的實現(只顯示位置的實現):

models.py中

class Location(models.Model):
    # variable id and pk are always available
    location = models.CharField(max_length=100)
    country = models.ForeignKey("Country")

serializers.py中

class LocationsSerializer(serializers.ModelSerializer):
    country_id = serializers.Field(source='country.id')

    class Meta:
        model = Location
        fields = (
            'id',
            'location',
            'country_id',
        )

views.py中

class LocationAPIView(generics.RetrieveAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

urls.py中

url(r'^location/(?P<pk>[0-9]+)/$', views.LocationAPIView.as_view(), name='LocationAPIView')

我嘗試過:我認為我不需要修改模型和序列化程序,因為它在調用上面提到的域時適用於單個對象。 所以我嘗試在views.py實現LocationsViewSet並在urls.py添加了一個新的url,但是我失敗了。 知道如何實現它嗎? 也許只需在LocationAPIView中定義一個方法並更改定義類似於此的url:

url(r'^all_locations/$', views.LocationAPIView.get_all_locations(), name='LocationAPIView')

在此先感謝,我將不勝感激任何幫助。

最好的問候,邁克爾

首先,讓我們暫時忘記視圖集 - 它們使一些事情變得更簡單,但它們還引入了一個額外的抽象層,我認為你現在不應該關注它。

您提到需要的第一件事是與當前詳細端點等效的列表端點。 你已經有了這個,你只需要在現有視圖旁邊引入一個額外的視圖。

views.py

class LocationListAPIView(generics.ListAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

class LocationDetailAPIView(generics.RetrieveAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

現在在URLconf中連接兩個視圖。

urls.py

url(r'^location/$', views.LocationListAPIView.as_view(), name='location-list'),
url(r'^location/(?P<pk>[0-9]+)/$', views.LocationDetailAPIView.as_view(), name='location-detail')

請注意,我還更改了URL名稱樣式,使其更符合通常的Django約定。

接下來,您需要一個位置+國家/地區的組合視圖。 您不僅可以使用現有的通用視圖,因為它是相當自定義的行為,但是為...編寫視圖很容易

views.py

class CombinedAPIView(APIView):
    def get(self, request):
        locations = Location.objects.all()
        countries = Country.objects.all()

        location_serializer = LocationSerializer(locations, many=True)
        country_serializer = CountrySerializer(countries, many=True)

        return Response({
            'countries': country_serializer.data,
            'locations': location_serializer.data
        })

並將視圖連接起來。

urls.py

url(r'^combined/$', views.CombinedAPIView.as_view(), name='combined-list')

請注意,在生成響應時根本不需要使用序列化程序,您也可以在每個實例上提取所有必需的字段,在視圖中顯式構建響應數據,但這是一個很好的標准方法。將模型實例映射到數據字典。

希望這會給你足夠的開始。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM