Kyle Truong
Kyle Truong

Reputation: 2741

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.

Upvotes: 11

Views: 16768

Answers (3)

Serhii Zelenchuk
Serhii Zelenchuk

Reputation: 345

If u need change all fields for all items, just try this:

from shop.models import Product


Product.objects.filter(recommend=True).update(recommend=False)

U can use this in Django Shell. Have a nice time :)

Upvotes: 1

dursk
dursk

Reputation: 4445

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.

Upvotes: 7

praba230890
praba230890

Reputation: 2310

You should save the changes,

game = Game.objects.get(name="testb")
game.likes = 5
game.save()

Upvotes: 26

Related Questions