【发布时间】:2021-09-27 02:13:51
【问题描述】:
我正在使用 django rest 框架在 django 中创建第一个 rest api
我无法获取 json 格式的对象。序列化程序总是返回空对象 {}
models.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__'
views.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 with this shop shop_id already exists.', code='unique')]}
由于出现错误,它似乎正在尝试更新记录,但它应该只获取记录并将其序列化为 json。
【问题讨论】:
标签: django django-models django-rest-framework django-views django-serializer