簡體   English   中英

如何使用Django和rest_framework通過url中的外鍵檢索對象

[英]How to retrieve object by foreign key in the url using Django and rest_framework

假設我使用的是兩個簡單的模型:

class Location(models.Model):
    location_name = models.CharField(max_length=100)
    country = models.ForeignKey("Country")

class Country(models.Model):
    country_name = models.CharField(max_length=100)

要通過它的主鍵檢索對象,我定義了這樣的視圖和URL( 與我已解決的問題相關 ):

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

現在我想定義一個新視圖,它返回一個國家/地區所有位置/城市的列表。 我的想法是使用folling url定義(或類似)。

url(r'^location-by-country/(?P<country_pk>[0-9]+)/$', views.LocationByCountryListAPIView.as_view(), name='location-by-country-detail')

我正在尋找一段時間的答案,但可能我沒有使用正確的關鍵字。 如何實現我的視圖以使用網址中的外鍵? 我可以使用過濾器按country_pk過濾位置嗎?

編輯:這是我想出來的,但我不知道如何過濾外鍵:

class LocationByCountryIdAPIView(generics.GenericAPIView):        
    def get(self, request, country_pk):
        locations = Location.objects.all() # .filter(???)
        location_list = list()
        for location in locations:
            # now I would do something similar to this
            # or use a filter on locations instead of creating location_list 
            # and appending locations to it
            if location.country.pk == country_pk:
                location_list.append(location)        

        location_serializer = LocationSerializer(location_list, many=True)
        # or location_serializer = LocationSerializer(locations, many=True) when using filter

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

最好的問候,邁克爾

好的,現在我讓它自己運行了。 這是怎么回事:

class LocationByCountryListAPIView(generics.ListAPIView):
    def get(self, request, country_pk):
        # get the country by its primary key from the url
        country = Country.objects.get(pk=country_pk)

        locations = Location.objects.filter(country=country)
        location_serializer = LocationSerializer(locations, many=True)

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

我正在使用上面提到的網址定義:

url(r'^location-by-country/(?P<country_pk>[0-9]+)/$', views.LocationByCountryListAPIView.as_view(), name='location-by-country-detail')

無論如何,我不確定這個解決方案是否是最好的方法。 我將不勝感激如何改進我的解決方案。

最好的問候,邁克爾

暫無
暫無

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

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