尽管使用了filter()方法,但是django rest框架get()返回了多个对象

时间:2018-03-11 03:50:50

标签: django django-rest-framework

model.py,我有两个模特

class student(models.Model):
    name = models.CharField(max_length=255)
    registration_number = models.CharField(max_length=255)
    session = models.CharField(max_length=255)
    college = models.ForeignKey(to='college', on_delete=models.CASCADE)

    class Meta:
        db_table = 'student'


class semester(models.Model):
    semester = models.IntegerField()
    student = models.ForeignKey(to='student', on_delete=models.CASCADE)
    sgpa = models.FloatField()
    grade = models.CharField(max_length=255)
    is_fail = models.BooleanField(default=True)

    class Meta:
        db_table = 'semester'

Serializer类看起来像

class SemesterSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.semester
        fields = ('id', 'semester', 'sgpa', 'grade', 'is_fail',)

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.student
        fields = ('id', 'name', 'registration_number', 'college', 'session',)

views.py包含

class SemesterViewSet(viewsets.ModelViewSet):    
    def get_queryset(self):
        if 'semester' in self.kwargs:
            return models.semester.objects.filter(semester=self.kwargs['semester'])
        else:
            return models.semester.objects.all()

    lookup_field = 'semester'
    serializer_class = serializer.SemesterSerializer

网址格式

router = DefaultRouter()
router.register('semester', views.SemesterViewSet, base_name='semester')
urlpatterns = [
    url(r'', include(router.urls)),
]

当我尝试访问url/semester/8时,引发了MultipleObjectsReturned异常并显示get() returned more than one semester -- it returned 2!错误消息。在这里,我没有使用任何get()方法。为什么会这样,解决方案是什么?我需要显示学期的所有结果。

1 个答案:

答案 0 :(得分:2)

从视图中删除lookup_field或将其更改为lookup_field = 'id'
该错误是因为当您调用retrieve()方法时,在其内部调用get_object(),该查询与查询相似,类似于 <击>

<击>
semester.objects.get(semester=semester.objects.get(id=8).semester)

<击>

semester.objects.get(lookup_field=parameter)

示例:

semester.objects.get(semester=8)


因此,如果有超过1个学期的实例具有相同的semester值,则会引发错误

UPDATE-1
尝试覆盖视图中的retrieve()方法,

from rest_framework.response import Response


class SemesterViewSet(ModelViewSet):
    def get_queryset(self):
        if 'semester' in self.kwargs:
            return semester.objects.filter(semester=self.kwargs['semester'])
        else:
            return semester.objects.all()

    lookup_field = 'semester'
    serializer_class = SemesterSerializer

    def retrieve(self, request, *args, **kwargs): # Change is here <<
        serializer = self.get_serializer(self.get_queryset(), many=True)
        return Response(data=serializer.data)