假设我正在使用两个简单的模型:
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
})
最好的问候,迈克尔