I am using a view in django rest framework. In this view it takes an argument
lookup_field = 'city'
def list(self, request, city):
self.city = city
queryset = Neighborhood.objects.filter(city=self.city)
serializer = NeighborhoodSerializer(queryset, many=True)
model = Neighborhood
fields = 'neighborhood'
city = models.ForeignKey(City, null=True)
neighborhood = models.CharField(max_length=150, null=False)
/home/rickus/211hospitality/suitsandtables/backend/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 966
def get_prep_value(self, value):
value = super(AutoField, self).get_prep_value(value)
if value is None:
Update - My original answer was incorrect. List view doesn't actually work with the
lookup_url_kwarg attributes, those attributes are used by Rest Frameworks DetailView in the
get_object(self) method to retrieve a single instance using those lookup fields.
I've updated the answer so it overrides the
get_queryset(self) method to return the correctly filtered list. This is how ListView should be customised.
It looks like you haven't defined your ListView properly. The problem seems to be that you are trying to filter on the Cities Primary Key, which is an integer field, using a string that can't be parsed as an integer. I'll write up how I think your view should look presuming your trying to do your filtering based on some field on the City model.
# models.py class City(models.Model): name = models.CharField(max_length=32) class Neighbourhood(models.Model): city = models.ForeignKey(City) # views.py class NeighbourhoodListView(generics.ListAPIView): queryset = Neighbourhood.objects.all() serializer_class = NeighbourhoodSerializer def get_queryset(self): return self.queryset.filter(city__name=self.kwargs.get('city') # urls.py urlpatterns = [ url( r'^neighbourhood-list/(?P<city>[a-zA-Z]+)/$', NeighbourhoodListView.as_view(), name='neighbourhood-list', ) ]
This will filter your Neighbourhoods by the Cities name. If you want to filter Neighbourhoods by the cities Primary Key, then you should use:
# views.py class NeighbourhoodListView(generics.ListAPIView): queryset = Neighbourhood.objects.all() serializer_class = NeighbourhoodSerializer def get_queryset(self): return self.queryset.filter(city=self.kwargs.get('city')) # urls.py urlpatterns = [ url( r'^neighbourhood-list/(?P<city>\d+)/$', NeighbourhoodListView.as_view(), name='neighbourhood-list', ) ]
This fixes the view and url's to filter Neighbourhoods by the Cities Primary Key. This would be more performant because it doesn't need to perform a join between City and Neighbourhood.