V
V
val1n0r2019-10-29 01:14:04
Django
val1n0r, 2019-10-29 01:14:04

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:
                # именно тут нужен таймер который будет каждую минуту записывать в бд значение

Found this PHP script
<?
# восстановление бенза
$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']."'");
}

?>

I need the same working principle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-11-06
@Realmixer

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)

Two sql queries will be executed here:
The variant with separate "query / parse / update" operations, however, allows erroneous data to occur when someone else also updates the data in between operations. Then whoever is the last to make a record - that value will be in the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question