Django权限遍历多个外国钥匙
我有4个核心实体模型:
- 用户
- 可以是收藏的所有者或参与者
- 可以是收集
- 食谱
- 食谱有一个外键
- 步骤
- 一步有食谱的外键
以启用上述内容,我认为我需要一个模型以及一个模型(让我们称其为Collection Contributor)具有以下字段:
- 贡献者 - 这将是一个外键对于用户模型
- 集合的外键
这将是集合中
class Collection(models.Model):
...
contributors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='CollectionContributor')
集合- 在所有食谱中。如果我想将这些视图限制在用户可以访问的配方一部分的一部分的步骤中,我将如何做到这一点。本质上,如何管理需要遍历多个外国钥匙的权限?
我认为这可能是以下内容。但这似乎非常低效,如果实体深入多层,可能会导致性能问题。这是这样做的“正确”方式?
def someViewOfSteps(request):
collections = models.Collection.objects.filter(Q(contributors__in=request.user))
recipes = models.Recipe.objects.filter(Q(collection__in=collections))
steps = models.Step.objects.filter(Q(recipe__in==recipe))
return steps
那对吗?
I have 4 core entity models:
- User
- Can be an Owner or Participant on a Collection
- Collection
- Recipe
- A recipe has a foreign key to a collection
- Steps
- A step has a foreign key to a recipe
In order to enable the above, I think I need a model for each of them as well as a model (let's call it CollectionContributor) with the following fields:
- contributor - this would be a foreign key to the user model
- collection - this would be a foreign key to the collection
On the Collection then, I'd add a many to many field that looks like this:
class Collection(models.Model):
...
contributors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='CollectionContributor')
Now, let's say I want to provide a page that lists all "step" across all recipes. If I want to limit that view to those steps that are part of recipes that are part of collections that the user has access to, how would I do that. Essentially, how can I manage permissions that require traversal of multiple foreign keys?
I assumed it might be something like the following. But it seems terribly inefficient, and could lead to performance issues if entities go several layers deep. Is this the "right" way to do this?
def someViewOfSteps(request):
collections = models.Collection.objects.filter(Q(contributors__in=request.user))
recipes = models.Recipe.objects.filter(Q(collection__in=collections))
steps = models.Step.objects.filter(Q(recipe__in==recipe))
return steps
Is that right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以查询:
这将使用
加入
s,而不是…in…
带有子Queries的效率较低,尤其是在 mysql 中。You can query with:
This will use
JOIN
s instead of… IN …
with subqueries, which tend to be less efficient, especially in MySQL.