Home > Software design >  django save() refuses to update an existing record
django save() refuses to update an existing record

Time:12-09

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...

CodePudding user response:

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
  • Related