Here is my models.py:
JavaScript
x
8
1
SHOW = (
2
(0,"Ballers"),
3
(1,"Silicon-Valley")
4
)
5
6
class Show(models.Model):
7
show = models.IntegerField(choices=SHOW, blank=True, null=True)
8
Here is from my urls.py:
JavaScript
1
4
1
urlpatterns = [
2
path('<str:show>/', views.ShowList.as_view(), name='show-list'),
3
]
4
Here is the function from views.py:
JavaScript
1
4
1
class ShowList(generic.ListView):
2
def get_queryset(self):
3
return Show.objects.filter(show=self.kwargs['show'])
4
I want to be able to have the url look like this: https://www.mywebsite.com/ballers, but when I try to run it, I get this error: Field ‘show’ expected a number but got ‘ballers’. I know I can fix this by calling the url https://www.mywebsite.com/0, but I don’t want the url to look like that.
Advertisement
Answer
In Django it takes first argument as the value to pass into db (field), so basically with:
JavaScript
1
2
1
return Show.objects.filter(show=self.kwargs['show'])
2
it tries to look directly with passing value. DB-wise it knows ONLY integers for that matter. So instead of looking directly, try to make small change:
JavaScript
1
6
1
class ShowList(generic.ListView):
2
def get_queryset(self):
3
show_string = self.kwargs['show']
4
show_int = [show[0] for show in Show.SHOW if show[1].lower() == show_string.lower()][0]
5
return Show.objects.filter(show=show_int)
6
and also move choices inside the model:
JavaScript
1
7
1
class Show(models.Model):
2
SHOW = (
3
(0,"Ballers"),
4
(1,"Silicon-Valley")
5
)
6
show = models.IntegerField(choices=SHOW, blank=True, null=True)
7