我想为使用post api创建的每个对象返回user_id
。
我希望以
的形式输出[
{"info": {
"status": "SUCCESS",
"message": "User Details Successfully Uploaded"
},
"user_id": 10001
}
]
这是我的代码
Serializer.py
class UserDetailsSerializer(serializers.ModelSerializer):
"""docstring for UserDetailsSerializer"""
class Meta:
model = UserDetails
fields = ['user_id', 'user_email', 'user_full_name', 'user_token', 'patient_id', 'user_preferences']
read_only_fields = ['user_id']
Views.py
class UserDetailsViewSet(APIView):
def get(self, request):
queryset= UserDetails.objects.all()
serializer_class=UserDetailsSerializer(queryset,many=True)
return Response(serializer_class.data)
def post(self, request):
serializer_class_post=UserDetailsSerializer(data=request.data)
if serializer_class_post.is_valid():
try:
serializer_class_post.save()
return Response([{"info": {
"status": "SUCCESS",
"message": "User Details Successfully Uploaded"
},
"user_id": serializer_class_post.data
}], status=status.HTTP_201_CREATED)
except IntegrityError as e:
return Response([{"info": {
"status": "Error",
"message": "Error Uploading User Details"
}
}], status=status.HTTP_400_BAD_REQUEST)
return Response(serializer_class_post.errors, status=status.HTTP_400_BAD_REQUEST)`
models.py
class UserDetails(models.Model):
user_id = models.IntegerField(primary_key= True)
user_email = models.CharField(max_length=254)
user_full_name = models.CharField(max_length=200)
user_token = models.CharField(max_length=200)
patient_id = models.CharField(max_length=12, unique=True)
user_preferences = models.CharField(max_length=200)
class Meta:
managed = False
db_table = 'walnut_users'
def __str__(self):
return self.user_id
答案 0 :(得分:0)
将您的帖子更改为以下内容:
def post(self, request):
serializer_class_post=UserDetailsSerializer(data=request.data)
if serializer_class_post.is_valid():
try:
obj = serializer_class_post.save()
return Response([{"info": {
"status": "SUCCESS",
"message": "User Details Successfully Uploaded"
},
"user_id": obj.pk
}], status=status.HTTP_201_CREATED)
except IntegrityError as e:
return Response([{"info": {
"status": "Error",
"message": "Error Uploading User Details"
}
}], status=status.HTTP_400_BAD_REQUEST)
return Response(serializer_class_post.errors, status=status.HTTP_400_BAD_REQUEST)`
serializer.save()
返回新创建的对象;只需使用它并在你的回复中获得pk。
此外,API最佳实践是返回完整的对象表示;不仅仅是身份证。理想情况下,我会做你做过的事:{"data": serializer_post_data.data}
- >这将返回完整的嵌套表示。您仍然可以访问user_id
data.user_id
。但是,如果您确定您的用例,则上述代码将起作用。
由于user_id
是IntegerField和主键,因此Django希望您提供该字段的值。您在哪里为user_id分配值 - 您的API是否也发布了user_id的值。如果您想自动指定值,请将其更改为user_id = models.AutoField(primary_key=True)