Django queryset使用父字段进行注释

时间:2014-10-23 19:39:42

标签: django django-models django-queryset django-1.7

我尝试引用注释中的字段,就像F()对象所做的那样。

# Getting users in this particular Group (using GroupMediator to also get "joined" date)
GroupMediator.objects.filter(group=group).annotate(
   # GroupPosition is a user's title within a group, like "treasurer".
   position=GroupPosition.objects.filter(group=group, recipients=F('member')))

问题: F('member')寻找"会员" GroupPosition中的字段,但我希望得到"成员"来自GroupMediator的字段。

我试图在同一个查询中获得每个成员在该组中的位置我得到了所有成员。我试图提高效率,所以我不必使用for循环并查询每个成员以获得他们的位置。

我希望尽可能避免使用原始查询。我被卡住了。

型号:

class Group(models.Model):
    title = models.CharField(_("title"), max_length=60, blank=False)
    members = models.ManyToManyField(User, related_name='member_of_groups', verbose_name=_("members"), blank=True, through='GroupMediator')

class GroupMediator(models.Model):
    member = models.ForeignKey(User, related_name="group_mediators", verbose_name=_("member"), blank=False, editable=False)
    group = models.ForeignKey(Group, related_name="group_mediators", verbose_name=_("group"), blank=False, editable=False)
    joined = models.DateTimeField(_("created"), auto_now_add=True, editable=False)

class GroupPosition(models.Model):
    # This is its own model so many different custom positions can be created for each group.
    group = models.ForeignKey(Group, related_name="group_positions", verbose_name=_("group"), blank=False, editable=False)
    recipients = models.ManyToManyField(User, related_name='received_group_positions', verbose_name=_("recipients"), blank=True)
    title = models.CharField(_("title"), max_length=60, blank=False)

谢谢!我可能正在接近这个错误,任何建议都值得赞赏。

1 个答案:

答案 0 :(得分:0)

从Django 1.11开始,您可以使用$('ol.settings li').click(function(e) { ??? });

参考:https://docs.djangoproject.com/en/1.11/ref/models/expressions/#django.db.models.OuterRef