获取切片后,断言错误无法过滤查询

时间:2020-12-28 08:37:11

标签: python django django-models django-rest-framework django-views

我的models.py中有两个类

class Icd(models.Model):
 code = models.CharField(primary_key=True, max_length=6)

class Icd10(models.Model):
 officialorder = models.IntegerField(blank=True, null=True)

上述模型还有两个视图集

class IcdViewSet(viewsets.ModelViewSet):
 queryset = Icd.objects.all()[:10]
 serializer_class = IcdSerializer

class Icd10ViewSet(viewsets.ModelViewSet):
 queryset = Icd10.objects.all()[:10]
 serializer_class = Icd10Serializer

下面是我的序列化器

class IcdSerializer(serializers.HyperlinkedModelSerializer):
  class Meta:
    model = Icd
    fields = ['code']

class Icd10Serializer(serializers.HyperlinkedModelSerializer):
  class Meta:
    model = Icd10
    fields = ['officialorder']

还有我的 app/urls.py

router = routers.DefaultRouter()
router.register(r'', views.IcdViewSet)
router.register(r'icd10', views.Icd10ViewSet)
urlpatterns = [
   path('', include(router.urls))
]

主 urls.py

urlpatterns = [
path('icd/', include('app.urls')),

]

当我调用 localhost:8000/icd 时,我得到了正确的响应。当我调用 localhost:8000/icd/icd10 时,出现以下错误

AssertionError at /icd/icd10/
Cannot filter a query once a slice has been taken.
Request Method: GET
Request URL:    http://localhost:8000/icd/icd10/
Django Version: 3.1.4
Exception Type: AssertionError
Exception Value:    
 Cannot filter a query once a slice has been taken.

从 Icd10 模型中检索记录需要更改什么?

2 个答案:

答案 0 :(得分:0)

这可能对您有所帮助:

还没有人回答“为什么不喜欢这个?”你问题的一部分。 https://docs.djangoproject.com/en/1.8/ref/models/querysets/ 处给出了解释:

even though slicing an unevaluated QuerySet returns another unevaluated QuerySet, modifying it further (e.g., adding more filters, or modifying ordering) is not allowed, since that does not translate well into SQL and it would not have a clear meaning either.

答案 1 :(得分:0)

看起来你的网址有问题,因为它发生了冲突 你可以这样做

router = routers.DefaultRouter()
router.register(r'', views.IcdViewSet, basename="icd")
router.register(r'icd10/add_urls', views.Icd10ViewSet, basename="icd10")
urlpatterns = [
   path('', include(router.urls,"api"))
]