Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

369
Vistas
django save() refuses to update an existing record

I've got the below model and a function that I call from view.py to update a field within that model called unread_count. However, it keeps trying to create a record rather than update the existing one and I get the error shown below. I've included 2 print statements to show the records exist. I've tried various things to get it working but I'm not making any progress (besides tearing my hair out). Any help would be appreciated.

class RoomOccupier(TimeStampedModel):

    room = models.ForeignKey(Room, on_delete=models.CASCADE, db_index=True)
    occupier = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="+", db_index=True)
    unread_count = models.PositiveSmallIntegerField(default=0, blank=False)

    def __int__(self):  # __unicode__ for Python 2
        return self
@database_sync_to_async
def increment_unread(room_id):

    roomOccupiers = RoomOccupier.objects.filter(room_id=room_id)
    print(roomOccupiers)

    for roomOccupier in roomOccupiers:

        print(roomOccupier)
        roomOccupier.unread_count += 1
        roomOccupier.save()

    return true
<QuerySet [<RoomOccupier: RoomOccupier object (1)>, <RoomOccupier: RoomOccupier object (2)>]>
RoomOccupier object (1)
Exception inside application: NOT NULL constraint failed: chat_roomoccupier.created
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: chat_roomoccupier.created

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__
    return await self.application...etc...
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I would advise to update the querset in bulk, with .update(…) [Django-doc]:

from django.db.models import F

@database_sync_to_async
def increment_unread(room_id):
    RoomOccupier.objects.filter(room_id=room_id).update(
        unread_count=F('unread_count')+1
    )
    return True
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda