ValueError:&#34; <notification:notification =“”object =“”>&#34;需要为字段&#34;通知&#34;在此之前可以使用多对多关系

时间:2016-12-13 12:26:30

标签: django python-3.x django-models

我有这个型号:

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()

另一方面,我是这个&#34;静态&#34;类:

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(消息和聊天)时(消息和聊天被保存),我收到了这个错误:

ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.

在Google上进行研究,我尝试this,但这并没有解决我的问题。

使用debug,我检查了在调用Model构造函数时抛出的错误。

这是追踪:

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.

1 个答案:

答案 0 :(得分:1)

在保存之前,您无法将NotificationUser相关联。

因此,您必须首先保存Notification,然后才能添加receivers

notification = Notification(
    sender=sender,
    type=Notification.TYPE_CHAT_MESSAGE,
    data=json.dumps(data)
).save()
# If chat.get_other_users(sender) return a queryset
receivers = chat.get_other_users(sender)
for receiver in receivers:
    notification.receivers.add(receiver)
# or you can also simply assign the whole list as it's already empty after new create
# >>> notification.receivers = recievers
notification.send()