我在Django中收到(无法分配“11”:“通知”。要“通知”的用户必须是“用户”实例。)
下面是我的代码。我有2个模型发布和通知。无论何时任何用户喜欢任何帖子,我都会将其添加到通知表中。获取“无法分配“11”:“Notification.user\u to\u notify”必须是“user”实例。此错误我在Django中收到(无法分配“11”:“通知”。要“通知”的用户必须是“用户”实例。),django,django-models,Django,Django Models,下面是我的代码。我有2个模型发布和通知。无论何时任何用户喜欢任何帖子,我都会将其添加到通知表中。获取“无法分配“11”:“Notification.user\u to\u notify”必须是“user”实例。此错误 #Post model class Post(models.Model): title = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) image = model
#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)
如果从
postExists
中删除.id
,应该可以解决此问题
postExists = Post.objects.get(pk=post_id)
# posted_by is having relation with User
notification = Notification()
notification.user_to_notify = postExists.posted_by
因为user\u to\u notify
需要用户实例,而不是整数。但是,如果需要,您仍然可以使用integer,如下所示:
notification.user_to_notify_id = postExists.posted_by.id
在ForeignKey下面,django创建了一个带有\u id
的列,因此当您使用notification.user\u to\u notify\u id
时,可以在其中设置一个整数。有关更多信息,请参阅