我正在尝试创建一个卡路里信息API,以节省用户的卡路里摄入量。
If the user already exists,
If the item id is already mapped with that user, then add the items calorie count with that item for that user.
Url: /api/calorie-info/save/
Method: POST, Input: { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] }
Output: - Response Code: 201
我的模特:
class CalorieInfo(models.Model):
user_id = models.IntegerField(unique=True)
itemId = models.IntegerField(unique=True)
calorie_count = models.IntegerField()
我试过了:
class Calorie(APIView):
def post(self, request):
data = json.loads(request.body.decode("utf-8"))
user_id = data['user_id']
for i in data['calorie_info']:
entry = CalorieInfo(user_id=user_id, item_id=i['itemId'], calorie=i['calorie_count'])
entry.save()
res = {"status": "success"}
return Response(res, status=status.HTTP_201_CREATED)
上面的代码工作正常,但是如何检查代码中的上述条件?
问题来源:stackoverflow
您需要像这样检查:
def post(self, request):
data = json.loads(request.body.decode("utf-8"))
user_id = data['user_id']
# fetch calorieinfo object for given user
user_calorieinfo = CalorieInfo.objects.filter(user_id=user_id)
# if user exists
if user_calorieinfo:
# ifCalorieInfo item mapped with user
for i in data['calorie_info']:
if CalorieInfo.objects.filter(user_id=user_id,itemId=i['itemId']:
for obj in CalorieInfo.objects.filter(user_id=user_id,itemId=i['itemId']):
updated_count = obj.calorie_count + i['calorie_count']
CalorieInfo.objects.filter(user_id=user_id,itemId=i['itemId']).update(calorie_count= updated_count)
else:
entry = CalorieInfo(user_id=user_id, item_id=i['itemId'], calorie=i['calorie_count'])
entry.save()
else:
for i in data['calorie_info']:
entry = CalorieInfo(user_id=user_id, item_id=i['itemId'], calorie=i['calorie_count'])
entry.save()
res = {"status": "success"}
return Response(res, status=status.HTTP_201_CREATED)
希望这会成功!
#for getting CalorieInfo object
def get(self):
id = request.GET.get('user_id')
user_calorieinfo = CalorieInfo.objects.filter(user_id=user_id)
response["user_id"] = id
response["calorie_info"] = []
for obj in user_calorieinfo:
response["calorie_info"].append({"itemId":obj.itemID, "calorie_count":obj.calorie_count})
response["status"] = success
return Response(response, status=status.HTTP_200_OK)
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。