m2m Django 权限模型
我正在构建的 Web 应用程序上的用户拥有多个“他们的”对象。让我们假设该对象名为 Toy
。
我希望他们能够为其玩具
设置隐私选项,以便他们可以设置以下可见性选项:
- 朋友的朋友
- 朋友
- 仅允许一组已定义的人
- 仅限朋友,但拒绝一组人(对某些人保密)
所以说我有这样的模型:
class User(models.Model): # actually a profile but simplifying
friends = models.ManyToManyField(User, through='Friendship')
class Toy(models.Model):
owner = models.ForeignKey(User)
我正在努力了解如何对权限数据和逻辑进行分层。
我可以添加一个存储上述选择的 permission_state
变量,然后为选项 #3 和 #4 设置 m2m,或者为 DENY 和 ALLOW 设置单独的 m2ms。
但是给定一个用户
,我如何过滤用户可以看到的所有玩具,而无需执行无数不同的查询?理想情况下,我希望在一次数据库访问中生成一个 Toy
对象列表。
或者我以错误的方式处理这个问题?
Users on a webapp I'm building have multiple objects that are "theirs" Let's pretend the object is called Toy
.
I want them to be able to set privacy options for their Toy
s so they can set the following visibility options:
- Friends of friends
- Friends
- Only allow a defined set of people
- Friends only, but deny a set of people (to keep it a secret from some people)
So say I have the models like so:
class User(models.Model): # actually a profile but simplifying
friends = models.ManyToManyField(User, through='Friendship')
class Toy(models.Model):
owner = models.ForeignKey(User)
I'm struggling to see how to layer on the permissions data and logic.
I could add a permission_state
variable that stored the above choice and then have a m2m for options #3 and #4, or have separate m2ms for DENY and ALLOW.
But given a User
, how would I filter for all toys that the user could see without doing umpteen different queries? I ideally want to generate a list of Toy
objects in one trip to the database.
Or am I approaching this the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我曾经必须解决类似的问题。我没有找到任何奇特的解决方案,因为我不需要健壮和干净的东西。这就是我所做的:
我创建了一个中间模型:
然后我为具有以下签名的视图编写了一些视图装饰器:
这些装饰器检查权限,然后直接在
extra_context
中设置一些变量,或特殊的kwarg
。这个解决方案一点也不完美,...但它可能对您有帮助!
但是,现在我重新阅读了您的问题,我不确定我是否准确回答了您的问题:
你的意思是,就像在facebook上一样:当用户A访问用户B的页面时,你只想显示用户A允许的用户B的玩具?
I had to solve a similar problem once. I didn't find any fancy solution, for I didn't need something robust and clean. Here's what I did :
I created a intermediate model :
Then I wrote some view decorators for views that have the following signature :
These decorators check the permissions, and then set some variables, either directly in the
extra_context
, or a specialkwarg
.This solution is not perfect at all,... but it might help you !
However, now that I re-read your question, I am not sure I answer exactly to what you asked :
Do you mean, like on facebook : when a user A visits a user B's page, you want to display only toys from user B that are allowed to user A ?