在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()
方法。为什么会这样,解决方案是什么?我需要显示学期的所有结果。
答案 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)