首页 > 解决方案 > 我在 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)

标签: djangodjango-models

解决方案


如果您从中删除.idpostExists那应该可以解决问题

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


推荐阅读