Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing model field within the Django Shell

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.

like image 388
Kyle Truong Avatar asked Oct 02 '15 02:10

Kyle Truong


People also ask

How do you add a new field to a model with new Django migrations?

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.

What are the fields in Django model?

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.


2 Answers

You should save the changes,

game = Game.objects.get(name="testb")
game.likes = 5
game.save()
like image 55
praba230890 Avatar answered Nov 15 '22 21:11

praba230890


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.

like image 32
dursk Avatar answered Nov 15 '22 20:11

dursk