如何根据与之相关的模型过滤模型?下面的示例......这可行,但我认为这会两次命中数据库并且非常不雅。有没有办法直接使用查询集来做到这一点?也许不知何故select_related()
,但一直无法弄清楚那个。我想返回一个QuerySet
。Project
from django.db import models
class Person(models.Model):
pass
class Project(models.Model):
pass
class Action(models.Model):
person = models.ForeignKey(Person)
project = models.ForeignKey(Project)
# Better way to do this?
def projects_by_person(person):
actions = Action.objects.filter(person=person)
project_ids = actions.values_list('project')
return Project.objects.filter(id__in=project_ids)