gpt4 book ai didi

python - Django - 限制查看项目的用户

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:58 26 4
gpt4 key购买 nike

我的模型:

class PromoNotification(models.Model):
title = models.CharField(_('Title'), max_length=200)
content = models.TextField(_('Content'))
users = models.ManyToManyField(User, blank=True, null=True)
groups = models.ManyToManyField(Group, blank=True, null=True)

我想将项目发布到具有某些权限的模板。该模板仅显示列表中用户(用户或/和组)的通知。我应该怎么办?感谢您的任何帮助。如果可以,请告诉我一些代码。

最佳答案

您可以使用自定义管理器,这样可以更轻松地在多个 View 中进行用户过滤。

class PromoNotificationManager(models.Manager):
def get_for_user(self, user)
"""Retrieve the notifications that are visible to the specified user"""
# untested, but should be close to what you need
notifications = super(PromoNotificationManager, self).get_query_set()
user_filter = Q(groups__in=user.groups.all())
group_filter = Q(users__in=user.groups.all())
return notifications.filter(user_filter | group_filter)

将经理连接到您的 PromoNotification 模型:

class PromoNotification(models.Model):
...
objects = PromoNotificationManager()

那么在你看来:

def some_view(self):
user_notifications = PromoNotification.objects.get_for_user(request.user)

您可以在文档中阅读有关自定义管理器的更多信息:http://www.djangoproject.com/documentation/models/custom_managers/

关于python - Django - 限制查看项目的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com