Changing model field within the Django Shell
Solution 1
You should save the changes,
game = Game.objects.get(name="testb")
game.likes = 5
game.save()
Solution 2
Calling Game.objects.get()
retrieves the data from the database.
When you execute the statement Game.objects.get(name='test').likes = 5
, you are retrieving the data from the database, creating a python object, and then setting a field on that object in memory.
Then, when you run Game.objects.get(name='test')
again, you are re-pulling the data from the database and loading a python object into memory. Note that above, when you set likes
to 5
, you did that purely in memory and never saved the data to the database. This is why when you re-pull the data, likes
is 0
.
If you want the data to be persisted, you have to call game.save()
after setting the likes
field. This will enter the data into the database, so that the next time you retrieve it via .get()
, your changes will have persisted.
Kyle Truong
Updated on June 20, 2022Comments
-
Kyle Truong almost 2 years
Is there anyway to use the Django shell to modify a field value? I can create, delete, and query models, but I don't know how to alter existing field values.
class Game(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Game, self).save(*args, **kwargs) def __str__(self): return self.name
In the Django shell, I try
Game.objects.get(name="testb").likes = 5
, but it still outputslikes = 0
when I inputGame.objects.get(name="testb").likes
right afterwards. -
Kyle Truong over 8 yearsThat was much simpler than I thought it would be... Thanks for the help, works perfectly