【问题标题】:AttributeError: 'Account' object has no attribute 'exclude'AttributeError:“帐户”对象没有属性“排除”
【发布时间】:2021-03-15 10:31:31
【问题描述】:

我建立了通知系统,我想在给自己的帖子添加赞时排除帖子的作者,所以收到通知,我遇到了这个问题

我的看法

def add_remove_like(request, pk):
data = {}
video = Video.objects.get(pk=pk)

if request.method == "POST":
    user = request.user
    if video.likes.filter(id=user.id).exists():
        liked = False
        video.likes.remove(user)
    else:
        video.likes.add(user)

        instance = video.author
        content_type = ContentType.objects.get_for_model(instance)

        try:
            notify = Notify.objects.create(from_user=request.user.exclude(from_user=instance), target=instance, content_type=content_type,
                                           redirect_url=f"{settings.BASE_URL}/video/account/video/{video.pk}",
                                           object_id=instance.pk,
                                           verb=f"{request.user} added like to your video"
                                           )
            notify.timestamp = timezone.now()
            notify.save()

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

    request.user 是一个对象,而不是查询集。所以exclude 在这里不起作用。所以你可以像这样更新代码:

    from_user = request.user if request.user != instance else None
    notify = Notify.objects.create(
        from_user= from_user,
        target=instance,
        content_type=content_type,
        redirect_url=f"{settings.BASE_URL}/video/account/video/{video.pk}",
        object_id=instance.pk,
        verb=f"{request.user} added like to your video",
        timestamp=timezone.now()
    )
    

    我已经删除了像 notify.save() 这样的其他代码,因为如果您在查询集的 create 方法中添加时间戳,它是重复的。

    【讨论】:

    • 感谢您的回答,帖子的作者仍然收到他添加到帖子中的喜欢
    • @MohamedSoliman 基本上,@ruddra 已经解决了 AttributeError 的问题,但是如果您不希望作者收到自己的通知,则需要添加额外的检查,例如: if video.author != request.user,然后创建Notify,否则什么都不做。
    • @ErsainD 谢谢,我添加了if request.user == instance:
    猜你喜欢
    • 1970-01-01
    • 2022-07-16
    • 1970-01-01
    • 2018-02-21
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多