简体   繁体   中英

How to use generic view with pk renamed

django.views.generic.detail.DetailView uses pk or slug from urls.py as the identifier. In my case, I have:

urls.py :

urlpatterns = [
    path('<int:quiz_id>/results/', views.ResultsView.as_view()),
]

Is there a way to use:

class ResultsView(generic.DetailView):
    model = Quiz

without changing quiz_id to pk (default name used for primary key)?

I expect that there is some way to change the vague pk to something more descriptive.

In ancestors (MRO) , there is django.views.generic.detail.SingleObjectMixin listed. You can override pk_url_kwarg of this class to change pk to quiz_id :

class ResultsView(generic.DetailView):
    model = Quiz
    pk_url_kwarg = "quiz_id"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM