【问题标题】:Adding instances into a different model将实例添加到不同的模型中
【发布时间】:2018-03-23 16:58:25
【问题描述】:

我正在尝试为我的 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 字段是提交操作(喜欢、评论等)的用户。

我的问题是我如何才能超越它,以便每当有人喜欢帖子或 cmets 并因此触发 LikePostToggle 视图时,它还会向 UserNotification 模型添加一个实例,以便通知用户?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以使用UserNotification() 创建一个实例,然后调用 save(),或者您可以使用create 快捷方式。

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

    obj.likes.add(user)
    #Add notification to UserNotification model
    notification = UserNotification.objects.create(
        user=self.request.user,
        post=obj,
        notify_type="???"
    )
    

    【讨论】:

    • 给我错误NameError at /feed/post/5/like/ name 'request' is not defined
    • 并且在创建后不向UserNotification 模型添加实例。
    • 如果它是基于类的视图中的方法,它应该是self.request 而不是request。
    猜你喜欢
    • 2013-06-19
    • 2015-06-17
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多