I'm trying to create a Calorie Info API which saves calorie intake for a user.
- If it is a new user, then add an entry for the user id and item id.
If the user already exists,
- If the item is new, then just map the item id and the calorie count with that user.
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
My model:
class CalorieInfo(models.Model):
user_id = models.IntegerField(unique=True)
itemId = models.IntegerField(unique=True)
calorie_count = models.IntegerField()
I tried:
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)
The above code works fine but how can I check the above conditions in my code ?