将实例添加到其他模型中

时间:2017-10-11 21:42:41

标签: python django

我正在尝试为我的Django项目制作一个通知应用程序。

我认为这是我的观点之一:

class LikePostToggle(RedirectView):
    def get_redirect_url(self,pk):
        obj = get_object_or_404(UserPost,pk=pk)
        user = self.request.user
        if user.is_authenticated():
            if user in obj.likes.all():
                obj.likes.remove(user)
            else:
                obj.likes.add(user)
                #Add notification to UserNotification model
                #Auto fill all fields
        return obj.get_absolute_url()

这是我的UserNotification模型:

class UserNotification(models.Model):
    user = models.ForeignKey(User,related_name='user',null=True)
    post = models.ForeignKey('feed.UserPost',related_name='post-notification')
    timestamp = models.DateTimeField(auto_now_add=True)
    notify_type = models.CharField(max_length=6)
    read = models.BooleanField(default=False)

    def __str__(self):
        return self.user

在模型中,我认为我希望user字段是提交动作的用户(喜欢,评论等)。

我的问题是我怎样才能做到这一点,以便每当有人喜欢帖子或评论并因此触发LikePostToggle视图时,它还会向UserNotification模型添加一个实例,以便用户可以收到通知?

1 个答案:

答案 0 :(得分:1)

您可以使用embed创建实例,然后调用save(),也可以使用UserNotification()快捷方式。

在视图中,您可以访问帖子和登录用户。时间戳将自动添加,create将默认为read,因此您只需决定将False设置为:

notify_type
相关问题