开发者

Django: Simplifying long 'join's?

开发者 https://www.devze.com 2023-01-31 01:54 出处:网络
I\'ve got a few long queries (for checking capabilities) which look like this: widgets = Widget.objects.filter(

I've got a few long queries (for checking capabilities) which look like this:

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

Is there any reasonable way of simplifying that query? Or do I just need to live with it?

The relevant models are:

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.ManyToMa开发者_如何学Gony(Capability)

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


You don't need to wrap your parameters in Q() objects, you can use the key/value pairs directly:

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

精彩评论

暂无评论...
验证码 换一张
取 消