Skip to content Skip to sidebar Skip to footer

Model Filed Values Are Not Updating In Django

Am building this voting platform, users will have to but the votes. They will input the number of votes to they want to buy, then make payment. After a successful payment, The numb

Solution 1:

No need to perform separate queries to get the value (first) and then to increment (second). Just use an F expression to access a field from the same model and perform an increment in a single operation:

from django.db.models import F

Nomination.objects.filter(slug=slug).update(votes=F('votes') + amount)

No need to cast Nomination.votes to int because it already is. But if amount is an str (though better if you accept it in your URL as an int to avoid conversions such as this):

Nomination.objects.filter(slug=slug).update(votes=F('votes') + int(amount[:-2]))  # The slice [:-2] was used as performed in the question. Adjust accordingly depending on what the amount really contains.

Here, all Nomination objects with the target slug would have their votes incremented by the said amount.


Update

Since we need the count of votes, we should not just accept the amount here since it is already the product of votes * price. What we can do is change the call to this API and include votes by changing nomination_payView() specifically this line:

"redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}",

To something like:

"redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}?votes={request.POST['votes']}",

Or:

"redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}/{request.POST['votes']}",
  • What you would choose depends on what is possible to be processed by the endpoint https://test.theteller.net/checkout/initiate as it will do the redirect.

Then within this process_payment API, we can simply access that count directly from the query parameters:

Nomination.objects.filter(slug=slug).update(votes=F('votes') + int(request.GET['votes']))

Or if you chose the 2nd option from path parameters

Nomination.objects.filter(slug=slug).update(votes=F('votes') + votes)  # Assuming you defined the URL as something like<path("process-payment/{str:slug}/{int:amount}/{int:votes}", ...>and the viewfunctionas<def process_payment(request, slug, amount, votes):>

Post a Comment for "Model Filed Values Are Not Updating In Django"