3

假设我正在使用两个简单的模型:

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')

现在我想定义一个新视图,它返回一个国家/地区所有位置/城市的列表。我的想法是使用以下 url 定义(或类似的)。

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

我一直在寻找答案,但可能我没有使用正确的关键字。我将如何实现我的视图以使用来自 url 的外键?我可以使用过滤器按 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
        })

最好的问候,迈克尔

4

1 回答 1

2

好的,现在我自己运行了。事情是这样的:

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 定义:

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

无论如何,我不确定这个解决方案是否是最好的方法。我将不胜感激有关如何改进我的解决方案的任何建议。

最好的问候,迈克尔

于 2013-08-30T12:56:25.773 回答