T. Rode
T. Rode

Reputation: 86

How to interact with integer field in Django SQLite Database?

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?

Upvotes: 1

Views: 596

Answers (1)

Selcuk
Selcuk

Reputation: 59184

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

Upvotes: 3

Related Questions