为什么djangorest在简单的GET请求上返回空的方括号?

huangapple go评论67阅读模式
英文:

Why is djangorest returning blank brackets on simple get request

问题

我试图返回一个数据库记录的列表视图。在测试中,我的数据库有三条记录。当调用我的视图函数时,它返回了3个空的花括号,而不是应该返回的项。这里有什么问题?序列化器、URL如下所示。我没有运行任何特殊的设置。

# 视图
@api_view(['GET'])
def getTheWashers(request):
    if request.method == "GET":
        washer = DishDoer.objects.all()
    
    washer_serializer = DishDoerSerializer(washer, many=True)
    return Response(washer_serializer.data)

# 序列化器
class DishDoerSerializer(serializers.ModelSerializer):
    class Meta:
        model = DishDoer 
        fields = "__all__"

# URL
urlpatterns = [
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls')), 
    path('api/washers', getTheWashers), 
]
英文:

I am trying to return a list view of a database records. In testing my database has three records. When my view function is called it returns 3 empty curly brackets instead of the items it should. What is wrong here? The serializer, url and included below. I am not running any special settings.

#view
@api_view(['GET'])
def getTheWashers(request):
    if request.method == "GET":
        washer = DishDoer.objects.all()
    
    washer_serializer = DishDoerSerializer(washer, many=True)
    return Response(washer_serializer.data)```


#seriaizer
class DishDoerSerializer(serializers.Serializer):
    class Meta:
        model = DishDoer 
        fields = "__all__"

#url
urlpatterns = [
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls')), 
    path('api/washers', getTheWashers), 
]

答案1

得分: 1

The issue seems to be with your serializer. Instead of inheriting from serializers.Serializer, you should inherit from serializers.ModelSerializer since you want to use all the fields from your DishDoer model.

class DishDoerSerializer(serializers.ModelSerializer):
    class Meta:
        model = DishDoer 
        fields = "__all__"
英文:

The issue seems to be with your serializer. Instead of inheriting from serializers.Serializer, you should inherit from serializers.ModelSerializer since you want to use all the fields from your DishDoer model.

class DishDoerSerializer(serializers.ModelSerializer):
    class Meta:
        model = DishDoer 
        fields = "__all__"

huangapple
  • 本文由 发表于 2023年5月6日 23:58:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定