Let's say I'm using the two simple models:
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)
To retrieve an object by it's primary key I defined views and urls like this (related to my resolved question):
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')
Now I like to define a new view which returns me a list of all locations/cities which are in a country. My idea is to use the folling url definition (or similar).
url(r'^location-by-country/(?P<country_pk>[0-9]+)/$', views.LocationByCountryListAPIView.as_view(), name='location-by-country-detail')
I was searching for an answer for a while, but probably I'm not using the right keywords. How would I implement my view to use a foreign key from the url? Could I use filters to filter locations by the country_pk?
Edit: This is what I came up with, but I don't know how to filter for the foreign key:
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
})
Best regards, Michael