1

How to update an integer field in a SQLite DB managed with Django models?

Extract of my Django models :

class Event(models.Model):
  title = models.CharField(max_length=100)
  [...]
  attendees = models.ManyToManyField(Attendee)
  max_attendees = 8
  #max_attendees = models.PositiveSmallIntegerField(null=True, blank=True)

Testing with python3 manage.py shell

>>> from main.models import *
>>> Event.objects.first()
<Event: 8 places left>
>>> Event.objects.first().max_attendees
8
>>> Event.objects.first().max_attendees = 2
>>> Event.objects.first().save()
>>> Event.objects.first().max_attendees
8

As you can see, the value is not updated even with a save() on the "object".

I have also tried :

>>> Event.objects.first().max_attendees = models.PositiveSmallIntegerField(2)

But it's not updating the value of max_attendees either. How can I modify the value of this field?

1 Answer 1

3

You have two issues. One, max_attendees is not a database field, it is a constant value. Change it to:

class Event(models.Model):
   ...
    max_attendees = models.PositiveSmallIntegerField(default=8)

You may have to run python manage makemigrations and python manage migrate after this change.

Second, each time you call Event.objects.first() you are creating a new object using the existing database record. You should assign the instance to a variable and use that until you are finished, i.e:

>>> my_event = Event.objects.first()
>>> my_event.max_attendees = 2
>>> my_event.save()

You can then re-query the data written:

>>> Event.objects.first().max_attendees
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.