Django:简化漫长的'加入'?

时间:2010-12-18 21:28:15

标签: django django-orm

我有一些长查询(用于检查功能),如下所示:

widgets = Widget.objects.filter(
    Q(owner__memberships = current_user),
    Q(owner__memberships__memberships__capabilities__name = "widget_list")
)

有没有合理的方法来简化查询?或者我只需要忍受它吗?

相关模型是:

class Widget(m.Model):
    owner = m.ForeignKey(Group)

class Group(m.Model):
    memberships = m.ManyToManyField(User, through=GroupMembership)

class GroupMembership(m.Model):
    user = m.ForeignKey(User)
    group = m.ForeignKey(Group)
    capabilities = m.ManyToMany(Capability)

class Capability(m.Model):
    name = m.CharField(...)

1 个答案:

答案 0 :(得分:1)

您不需要将参数包装在Q()对象中,您可以直接使用键/值对:

widgets = Widget.objects.filter(
    owner__memberships = current_user,
    owner__memberships__memberships__capabilities__name = "widget_list"
)