Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda