【发布时间】:2022-01-12 23:38:33
【问题描述】:
我有下面的模型和一个从 view.py 调用的函数,用于更新该模型中名为 unread_count 的字段。但是,它一直在尝试创建记录而不是更新现有记录,我收到如下所示的错误。我已包含 2 个打印语句以显示记录存在。我已经尝试了各种方法来让它工作,但我没有取得任何进展(除了扯掉我的头发)。任何帮助将不胜感激。
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...
【问题讨论】:
-
可以分享
TimeStampedModel吗? -
我看到了这部分错误:
NOT NULL constraint failed: chat_roomoccupier.created此模型上是否存在一个已创建字段?如果答案是肯定的,是否已运行迁移? -
TimeStampedModel 是我导入的,所以我不确定内部工作原理,但它基本上为每条记录添加了创建和修改的日期/时间戳。我确实尝试删除它以检查它是否导致问题,除了它在我的应用程序中的其他地方使用并删除它导致许多其他错误。但是,Willem 的回答奏效了,但不确定原因。