Reputation: 397
I am doing a Save in every move of my django project (a game actually), and all I am trying to do is to get the LAST data I saved in the database in every new "click".
newsave = Save()
newsave.user = save.user
myList = json.loads(newsave.myField) # Read previous here, here is the problem
... (do some changes on myList) ...
newsave.myField = json.dumps(myList) # Save the new move, UPDATED
The problem is that I don't know how to read the previous move correctly.
Upvotes: 0
Views: 763
Reputation: 542
Maybe django signals would help? https://docs.djangoproject.com/en/1.11/ref/signals/#pre-save or https://docs.djangoproject.com/en/1.11/ref/signals/#post-save?
Upvotes: 0
Reputation: 7707
First of all, you might want to rename your model from Save to something else as it will make your code much more easier to understand.(Django models already have a built in save() method)
One technique to handle this is by overriding the save() method of your model.In this case, you need the last record and not last-1 as the current record is not yet in the db.
Make sure that your model is storing the date&time of the last move so that you can accurately track the moves.
from datetime import datetime
class Yourmodel(models.Model):
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
self.modified = datetime.now()
#Get the last object, current object havent inserted to db yet.
lastmove = Yourmodel.objects.latest('modified')
#do something to your lastmove.myfield here
#you can access the current myfield using self.myfield
return super(Yourmodel, self).save(*args, **kwargs)
Upvotes: 1