gpt4 book ai didi

python - Django url 中的多个 pks

转载 作者:行者123 更新时间:2023-11-30 22:58:27 26 4
gpt4 key购买 nike

我目前正在尝试使用 Django Rest Framework 构建 API。目前我希望能够在一个 url 中拥有多个 pks,但是当我尝试时出现错误:

django.core.exceptions.ImproperlyConfigured: "^video/(?P[0-9]+)/quiz/(?P[0-9]+)/list/$" is not a valid regular expression: redefinition of group name 'pk' as group 2; was group 1 at position 31

这是我的网址:

url(r'^video/(?P<pk>[0-9]+)/quiz/(?P<pk>[0-9]+)/list/$',
views.QuizList.as_view(),
name='quizzes-list'),
url(r'^video/(?P<pk>[0-9]+)/quiz/(?P<pk>[0-9]+)/detail/$',
views.QuizDetail.as_view(),
name='quizzes-detail'),

我将对一个视频进行多个测验,并希望能够通过我的网址中的某个 pk 到达它们。

是否有一个简单的方法可以做到这一点,或者我缺少正确的方法来做到这一点?

谢谢

编辑*以下是我的观点:

class VideoList(generics.ListCreateAPIView):
queryset = Video.objects.all()
serializer_class = VideoSerializer


class VideoDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Video.objects.all()
serializer_class = VideoSerializer


# quiz
class QuizList(generics.ListCreateAPIView):
queryset = Quizzes.objects.all()
serializer_class = QuizSerializer


class QuizDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Quizzes.objects.all()
serializer_class = QuizSerializer

更新的网址:

    ###
# Quiz urls
###

url(r'^video/(?P<pk1>[0-9]+)/quiz/(?P<pk2>[0-9]+)/list/$',
views.QuizList.as_view(),
name='quizzes-list'),
url(r'^video/(?P<pk1>[0-9]+)/quiz/(?P<pk2>[0-9]+)/detail/$',
views.QuizDetail.as_view(),
name='quizzes-detail'),

更新的 View :

class QuizList(generics.ListCreateAPIView):
queryset = Quizzes.objects.all()
serializer_class = QuizSerializer

def get(self, request, *args, **kwargs):
pk1 = kwargs.get('pk1', None)
pk2 = kwargs.get('pk2', None)
print(pk1)
print(pk2)
return self.list(request, *args, **kwargs)

新错误:

Could not resolve URL for hyperlinked relationship using view name "quizzes-list". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

最佳答案

您必须为命名捕获组指定唯一的名称。

url(r'^video/(?P<pk1>[0-9]+)/quiz/(?P<pk2>[0-9]+)/list/$',
views.QuizList.as_view(),
name='quizzes-list'),

通过访问 View 中对应的pk*值,

pk1 = kwargs.get('pk1', None)
pk2 = kwargs.get('pk2', None)

例如:

# quiz
class QuizList(generics.ListCreateAPIView):
queryset = Quizzes.objects.all()
serializer_class = QuizSerializer

def get(self, *args, **kwargs):
pk1 = kwargs.get('pk1', None)
pk2 = kwargs.get('pk2', None)
print pk1
print pk2
return super(QuizList, self).get(*args, **kwargs)

关于python - Django url 中的多个 pks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com