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 outputs likes = 0
when I input Game.objects.get(name="testb").likes
right afterwards.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.
Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields.
You should save the changes,
game = Game.objects.get(name="testb")
game.likes = 5
game.save()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With