Ron*_*nak 1 django django-models django-views django-serializer django-rest-framework
我正在使用 django rest 框架在 django 中创建第一个rest api
我无法获取 json 格式的对象。序列化器始终返回空对象 {}
模型.py
class Shop(models.Model):
    shop_id = models.PositiveIntegerField(unique=True)
    name = models.CharField(max_length=1000)
    address = models.CharField(max_length=4000)
序列化器.py
class ShopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shop
        fields = '__all__'
视图.py
@api_view(['GET'])
def auth(request):
    username = request.data['username']
    password = request.data['password']
    statusCode = status.HTTP_200_OK
    try:
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                
                context_data = request.data
                
                shop = model_to_dict(Shop.objects.get(retailer_id = username))
                shop_serializer = ShopSerializer(data=shop)
                if shop:
                    try:
                        
                        if shop_serializer.is_valid():
                            print('is valid')
                            print(shop_serializer.data)
                            context_data = shop_serializer.data
                        else:
                            print('is invalid')
                            print(shop_serializer.errors)
                    except Exception as e:
                        print(e)
                else:
                    print('false')
            else:
                pass
        else:
            context_data = {
                    "Error": {
                        "status": 401,
                        "message": "Invalid credentials",
                        }
                    }
            statusCode = status.HTTP_401_UNAUTHORIZED
    except Exception as e:
        pass
    return Response(context_data, status=statusCode)
当我尝试打印print(shop_data)它总是返回空对象
有帮助吗,为什么对象是空的而不是返回 json 格式的 Shop 对象?
编辑:
我已经用下面提到的建议更新了代码。但现在,当执行 shop_serializer.is_valid() 时,我收到以下错误
{'shop_id': [ErrorDetail(string='该商店 shop_id 的商店已存在。', code='unique')]}
出现错误后,它似乎正在尝试更新记录,但它应该只获取记录并将其序列化为 json。
Serializer您在此代码片段中使用标准类:
class ShopSerializer(serializers.Serializer):
    class Meta:
        model = Shop
        fields = '__all__'
该类不会读取子类的内容Meta,也不会使用与模型类匹配的字段填充自身。您可能想改用ModelSerializer。
如果您确实想Serializer在此处使用该类,则需要自己使用正确的字段填充它。
| 归档时间: | 
 | 
| 查看次数: | 1976 次 | 
| 最近记录: |