Answer the question
In order to leave comments, you need to log in
How to increment a variable in a database?
Actually there is a problem, I teach django, I write a game on it.
I would like to implement a timer with a record in the database.
I will describe briefly:
There is a parameter - "energy", stored in the database (from 0 to 100)
I need to add +1 to the database every minute, up to 100
If the user spends energy, start recovery again.
While I see the work code like this:
get_energy = UserAttribute.objects.filter(user_id=uid).only('energy')
for i in get_energy:
if i.energy < 100:
# именно тут нужен таймер который будет каждую минуту записывать в бд значение
<?
# восстановление бенза
$currentDate = time();
$dateDiff = $currentDate - $user['fuel_time'];
$newFuel = $user['fuel'];
//30000 сек - время полной заправки...
if ($dateDiff < 30000 && $newFuel < $user['max_fuel'])
{
while ($dateDiff > 300){
$newFuel++;
if ($newFuel >= $user['max_fuel'])
{
break;
}
$dateDiff = $dateDiff - 300; //300 сек == 5 мин
}
}
else
{
$newFuel = $user['max_fuel'];
}
if ($newFuel != $user['fuel'])
{
mysql_query("UPDATE `user` SET `fuel`='$newFuel', `fuel_time`= '$currentDate' WHERE id='".$user['id']."'");
}
?>
Answer the question
In order to leave comments, you need to log in
It is better to try to avoid loops in the code if it is possible to perform data analysis and change at the database level in a minimum of transactions (although of course there are exceptions):
from django.db.models import F
UserAttribute.objects.filter(energy__lt=100).update(energy=F('energy') + 1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question