django - 我在 Django 中得到(无法分配“11”:“Notification.user_to_notify”必须是“用户”实例。)
问题描述
下面是我的代码。我有 2 个模型 Post 和 Notification。每当任何用户喜欢任何帖子时,我都会将其添加到通知表中。并得到'无法分配“11”:“Notification.user_to_notify”必须是“用户”实例。'这个错误。
#Post model
class Post(models.Model):
title = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/',blank=True)
posted_by = models.ForeignKey(User, on_delete=models.CASCADE)
#Notification model
class Notification(models.Model):
user_to_notify = models.ForeignKey(User, related_name = 'user_to_notify',on_delete=models.CASCADE)
user_who_fired_event = models.ForeignKey(User, related_name= 'user_who_fired_event' ,on_delete=models.CASCADE)
event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
seen_by_user = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
postExists = Post.objects.get(pk=post_id)
# posted_by is having relation with User
notification = Notification()
notification.user_to_notify = postExists.posted_by.id(ERROR)
#also tried
notification.user_to_notify = postExists.posted_by(Still getting ERROR)
解决方案
如果您从中删除.id
,postExists
那应该可以解决问题
postExists = Post.objects.get(pk=post_id)
# posted_by is having relation with User
notification = Notification()
notification.user_to_notify = postExists.posted_by
因为user_to_notify
需要一个用户实例,而不是一个整数。但是,如果您愿意,您仍然可以使用整数,如下所示:
notification.user_to_notify_id = postExists.posted_by.id
在 ForeignKey 下,django 创建一个带有 的列<field_name>_id
,所以当你使用 时notification.user_to_notify_id
,你可以在那里设置一个整数。更多信息可以在 中找到documentation
。
推荐阅读
- sql-server - EXECUTE 之后的事务计数指示 BEGIN 和 COMMITS 的数量不匹配
- python - 遍历 os.stat_result 中包含的所有结果并保留描述符
- google-cloud-pubsub - PubSub 订阅何时被视为不活动?
- python - 如何保存多维不同的数组形状
- java - 管道作业中的多个 Java 版本使用
- telegram-bot - Telegram Bot 在查询中使用按钮
- android - 将项目从 eclipse-adt 导出到 android studio 后出现奇怪的程序错误
- python - 通过拆分每列并迭代python pandas DataFrame中的许多列来插入新列
- javascript - 如何在反应中使用来自另一个文件的状态
- python - Python中的结构化流处理