0
を使用することができます前に、「通知」フィールドの値を持っている必要があり、私はこのモデルがあります、一方についてとValueError:「<通知:通知オブジェクトが>」この多対多の関係が
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()
を
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used.
0:、私はこのエラーを取得する(メッセージとチャットがpreviusly保存されている)
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、チャット):私はこの "静的" クラスをしました
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.
を追加することができますこれは、この問題を解決したが、今、私はTypeError例外を取得:「ManyRelatedManager」オブジェクトが反復可能ではありません。 戻り値self.users.exclude(pk = user.pk) 'self.users.exclude(pk = user.pk)'がループバックできるユーザのリストを返した場合、 –
が返されます。このリストを作成し、各ユーザを 'notification'オブジェクトに追加します。 'chat.get_other_users(送信者)のユーザ:' 'notification.receivers.add(user)' –
[除外](https://docs.djangoproject.com/ja/1.10/ref/models/querysets/#exclude)クエリーセットを返します。私が間違っていなければ、これはタプルです。 –