【发布时间】:2016-12-13 12:26:30
【问题描述】:
我有这个模型:
class Notification(BaseTimestampableModel):
# TYPES CONSTANTS HERE
# TYPE_CHOICES DICT HERE
sender = models.ForeignKey(User, related_name='sender_notifications')
receivers = models.ManyToManyField(User, related_name='receiver_notifications')
type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES)
data = models.TextField()
sent = models.BooleanField(default=False)
class Meta:
verbose_name = _('Notification')
verbose_name_plural = _('Notifications')
def send(self):
# Logic for sending notification here
self.sent = True
self.save()
另一方面,我有这个“静态”类:
class ChatNotifications:
@staticmethod
def message_created(message, chat):
"""
Send a notification when a chat message is created
to all users in chat except to the message's sender.
"""
sender = message.user
data = {
'text': message.text,
'phone': str(sender.phone_prefix) + str(sender.phone),
'chatid': chat.uuid.hex,
'time': timezone.now().timestamp(),
'type': 'text',
'msgid': message.uuid.hex
}
notification = Notification(
sender=sender,
receivers=chat.get_other_users(sender),
type=Notification.TYPE_CHAT_MESSAGE,
data=json.dumps(data)
)
notification.send()
但是当我调用 ChatNotifications.message_created(msg, chat) (消息和聊天已预先保存)时,我收到此错误:
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.
在谷歌上搜索,我尝试做this,但这并没有解决我的问题。
通过调试,我检查了调用模型构造函数时抛出的错误。
这是踪迹:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/vagrant/petycash/apps/chats/notifications.py", line 45, in message_created
data=json.dumps(data)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 550, in __init__
setattr(self, prop, kwargs[prop])
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
manager = self.__get__(instance)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
(instance, self.source_field_name))
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.
【问题讨论】:
标签: django python-3.x django-models