I have a model and I want to send increment a field value by 1 for multiple records. I searched for efficient update answers like Efficient way to update multiple fields of Django model object but they assume I have the value whereas I want to increment so the value might be different for different records.
My Model looks something like this:
class Signal(models.Model):
name = models.CharField(max_length=80)
version = models.IntegerField()
In my view, I want to send a list of names and then update all of their versions by 1.
My current method is to look through the names, create objects, update versions, and save manually so like this:
signals = Signal.objects.filter(name__in=signal_names)
for signal in signals:
signal.pk=None
signal.version = signal.version+1
signal.save()
This results in way too many queries and is very slow because I'll be sending 100s of names at once.
Is there a better way to do this?
NOTE: This might seem similar to bulk update questions but in this case I want to increment 1 so I dont have the value to update with. That was my struggle with existing answers.
Example:
signal table
name | version
n1 | 1
n2 | 2
I send ["n1", "n2"] in my post and the output should be
signal table
name | version
n1 | 1
n2 | 2
n1 | 2
n2 | 3
UPDATE One more contingency I found out is that the next time I want to update, I just want to update the latest version -- not all of them
So if I run the POST request again, the value should be
signal table
name | version
n1 | 1
n2 | 2
n1 | 2
n2 | 3
n1 | 3
n2 | 4
How can I filter to update the latest version for each name only? The database I'm using is "sql server"