Python 3.x Django Rest如何使用lookup_字段获取多个对象

Python 3.x Django Rest如何使用lookup_字段获取多个对象,python-3.x,django,api,django-rest-framework,django-views,Python 3.x,Django,Api,Django Rest Framework,Django Views,我想为我的api创建简单的过滤。我想在我的url中搜索的内容是: /api/视频问题集/2/ 并根据开发人员的请求,获取视频字段为2或任何其他数字的每个视频问题对象 我现在得到的错误是: get()返回了多个VideoQuestions——它返回了2个 这是我的密码: models.py class Questions(models.Model): """ Questions class for the e-learner overl

我想为我的api创建简单的过滤。我想在我的url中搜索的内容是: /api/视频问题集/2/

并根据开发人员的请求,获取视频字段为2或任何其他数字的每个视频问题对象

我现在得到的错误是:
get()返回了多个VideoQuestions——它返回了2个

这是我的密码:

models.py

    class Questions(models.Model):
    """
        Questions class for the e-learner overlay
    """
    question_text = models.CharField(max_length=150)
    answer = models.OneToOneField(QuestionAnswers, on_delete=models.CASCADE,
                                  related_name='correct_answer', null=True, blank=True)
    choices = models.ManyToManyField(QuestionAnswers, related_name='choices')

    class Meta:
        verbose_name_plural = "Questions"


class VideoQuestions(models.Model):
    """
        Categorize questions per video
    """
    video = models.ForeignKey(Video, on_delete=models.CASCADE)
    created = models.DateTimeField()
    question = models.ManyToManyField(Questions, blank=True, related_name='question')

    class Meta:
        verbose_name_plural = "learner questions"
views.py:

class VideoQuestionSet(viewsets.ModelViewSet):
    serializer_class = VideoQuestionSerializer
    queryset = VideoQuestions.objects.all()
    lookup_field = 'video'

    # def get_queryset(self):
    #     queryset = VideoQuestions.objects.all()
    #     video = self.request.query_params.get('video', None)
    #     if video is not None:
    #         queryset = queryset.filter(video=video)
    #     return queryset
my URL.py:

from django.conf.urls import include, url
from rest_framework import routers

from .views import VideoQuestionsListView, VideoQuestionSet



router = routers.DefaultRouter()
router.register(r'videoquestions', VideoQuestionsListView, basename='vq-list'),
router.register(r'videoquestionset', VideoQuestionSet, basename='vq-detail'),


urlpatterns = [
    url(r'', include(router.urls))
]
我尝试的是:

  • 使用正则表达式进行Django筛选,如/videoquestionset/?v=2。我真的搞不懂过滤,所以我又回到了我的旧代码

我更愿意在您的情况下使用URL过滤(您已经有了)


简言之,您的方法是正确的,但您尝试了错误的URL。

我更希望在您的情况下使用URL过滤(您已经使用了)


简而言之,你的方法是正确的,但你尝试了错误的URL。

哇,这么简单,真让我讨厌。因为这个,我一直在胡思乱想。非常感谢你,先生!哇,这么简单,真让我讨厌。因为这个,我一直在胡思乱想。非常感谢你,先生!
class VideoQuestionSet(viewsets.ModelViewSet):
    serializer_class = VideoQuestionSerializer

    def get_queryset(self):
        queryset = VideoQuestions.objects.all()
        video = self.request.query_params.get('video', None)
        if video:
            queryset = queryset.filter(video_id=int(video))
        return queryset
/videoquestionset/?video=2