Skip to content
Advertisement

In Django, how do I get the corresponding key for a value passed in through the url?

Here is my models.py:

SHOW = (
    (0,"Ballers"),
    (1,"Silicon-Valley")
)

class Show(models.Model):
    show = models.IntegerField(choices=SHOW, blank=True, null=True)

Here is from my urls.py:

urlpatterns = [
    path('<str:show>/', views.ShowList.as_view(), name='show-list'),
]

Here is the function from views.py:

class ShowList(generic.ListView):
    def get_queryset(self):
        return Show.objects.filter(show=self.kwargs['show'])

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:

return Show.objects.filter(show=self.kwargs['show'])

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:

class ShowList(generic.ListView):
    def get_queryset(self):
        show_string = self.kwargs['show']
        show_int = [show[0] for show in Show.SHOW if show[1].lower() == show_string.lower()][0]
        return Show.objects.filter(show=show_int)

and also move choices inside the model:

class Show(models.Model):
    SHOW = (
        (0,"Ballers"),
        (1,"Silicon-Valley")
    )
    show = models.IntegerField(choices=SHOW, blank=True, null=True)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement