Adding + 10 to (session field) and trying to save the data into (totalsession field),So that totalsession display on a table in the frontend in a new raw everytime the button is clicked. THANK YOU
VIEWS.PY
@api_view(['POST'])
def swimmersReduce(request, pk):
sw = get_object_or_404(Swimmers,id=pk) # gets just one record
current_sessions = sw.sessions + 10
sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record)
sw.save() # you may want to do this to commit the new value
serializer = SubSerializer(instance=sw, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED)
return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)
MODELS.PY
class Swimmers(models.Model):
name = models.CharField(max_length=200, blank=False)
lastname = models.CharField(max_length=200, blank=False)
idno = models.CharField(max_length=200, blank=False, null=True)
sessions = models.IntegerField(blank=False)
totalsessions = models.IntegerField(blank=True, null=True)
dateofpayment = models.CharField(max_length=200, blank=True)
Taking your question literally, you can just set the
totalsessionsto be equal tosw.sessionsand save the object again.However, I can't help but wonder if you are tracking total sessions across all Swimmers in this table? So one swimmer might have 10 sessions but you are tracking say 100 sessions across all swimmers but in each swimmer object. This isn't a good way of structuring your models. You should use Django's ORM aggregation if you want to manage the total number of sessions:
https://docs.djangoproject.com/en/4.0/topics/db/aggregation/
If you really want to store that in the database then I would suggest another model that tracks those numbers in a single object, rather than all of them.
As an aside, your model naming convention should be
Swimmerand not the pluralSwimmersEdit
To manage the swimming sessions in a better way, create a model like so, with a swimmer foreign key.
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
When a swimming session is created, you can specify which swimmer it relates to. Each swimmer can then have any number of swimming sessions, to get the number of swimming sessions per swimmer you can simply do:
To get the total number of sessions across all swimmers do: