Python 如何使用Django和rest_框架通过url中的外键检索对象
假设我使用两个简单的模型:Python 如何使用Django和rest_框架通过url中的外键检索对象,python,django,django-rest-framework,Python,Django,Django 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:
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:
致以最良好的祝愿,
迈克尔好的,现在我自己运行了。事情是这样的:
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')
url(r'^location by country/(?P[0-9]+)/$),views.LocationByCountryListAPIView.as_view(),name='location-by-country-detail')
无论如何,我不确定这个解决方案是否是最好的方法。如果您能给我一些建议来改进我的解决方案,我将不胜感激
致以最良好的祝愿,
迈克尔
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')