2

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 ?

2 Answers 2

1

you need to check like this:

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)

Hope this will work!

#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)
Sign up to request clarification or add additional context in comments.

8 Comments

Comments are not for extended discussion; this conversation has been moved to chat.
@code_nation just removed the loop in the updated answer!
Do you know how to get data in similar manner if i'm trying to get data for an id let say 1 and I get the response in same manner ? @MehaParekh
yes, you can pass the id and filter object of it and you need to set a dict because by default it will not return as you expect! If you wish I can add it to the answer! @code_nation
yes please, Thanks a lot.and the above code can't add any other itemId it works perfect for 1st time but if i change the ids and send it again it doesn't work. @MehaParekh
|
0

If user and item are representing an entity then you should have separate table for this. Those table should be used as foreign key in this table.

For user, Django already have auth.User model. So you do not have to create a seperate table for this

For item, you can define a table like this

class Item(models.Model):
    name = models.CharField(max_length=100)

Your table will become like this

class CalorieInfo(models.Model):
    user = models.ForeignKey(to='auth.User')
    item = models.ForeignKey(to='Item')
    calorie_count = models.IntegerField()

No need to write foreign keys like user_id or item_id as Django do it automatically to the foreign key. When will user foreign keys, Django will make sure if these objects which are referred with foreign keys already exist in database.

Your view will look like this

class CalorieView(APIView):

    def post(self, request):

        data = request.data
        for ci in data.get('calorie_info', []):
            clinfo, created = CalorieInfo.objects.update_or_create(
                user_id=data.get('user_id'),
                item=ci.get('itemId'),
                defaults={'calorie_count': ci.get('calorie_count')
            )
        return Response(
              {"status": "success"}, status=status.HTTP_201_CREATED)

2 Comments

What will be the query to get the data in same format for a particular id let's say user_id = 1? @Muhammad Hassan
CalorieInfo.objects.filter(user_id=1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.