简体   繁体   English

用于向后相关字段的 Django 查询集过滤器

[英]Django queryset filter for backwards related fields

How can you filter a model based on a model that relates to it?您如何根据与其相关的模型过滤模型? Example below...this works, but I think this hits the DB twice and is pretty inelegant.下面的示例......这有效,但我认为这两次击中数据库并且非常不优雅。 Is there a way to do it directly with querysets?有没有办法直接用查询集来做? Maybe somehow with select_related() , but haven't been able to figure that one out.也许以某种方式使用select_related() ,但一直无法弄清楚。 I want to return a QuerySet of Project .我想返回ProjectQuerySet

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)

Try this.试试这个。 I haven't tested it let me know if you have any issues我还没有测试过,如果您有任何问题,请告诉我

#Untested Code
Project.objects.filter(action__person = person)

Is it true that you have a many-to-many relation between Person and Project ? PersonProject之间是否存在多对多关系? If so, you can simplify your setup like this:如果是这样,您可以像这样简化您的设置:

class Person(models.Model):
    projects = models.ManyToManyField('Project')
    name = models.CharField(max_length=100)     # just an example

class Project(models.Model):
    # ... some fields here ...

You can then eg issue the following query to get all the projects from people who are called John:例如,您可以发出以下查询以从名为 John 的人那里获取所有项目:

Project.objects.filter(person_set__name="John")

The usage of select_related() can speed up the lookup a bit when you have lots of queries which follow relations between different database tables but you don't need it to accomplish what you want.当你有很多查询遵循不同数据库表之间的关系但你不需要它来完成你想要的时,使用select_related()可以稍微加快查找速度。

You can find my case at below:你可以在下面找到我的案例:

There are teachers and courses.有老师,有课程。 Teachers can have multiple course but course has done by only one teacher.教师可以有多门课程,但课程只能由一名教师完成。

class Course(models.Model):
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    -------

class Teacher(models.Model):
    name = models.CharField(max_length=50)
    ------

Inside the individual Teacher page I want to list all courses given by this individual teacher.在个别教师页面内,我想列出这位个别教师教授的所有课程。 You can find the related view function below.您可以在下面找到相关的视图功能。

def teacher(request, teacher_id):
teacher = get_object_or_404(Teacher, pk=teacher_id)
courses = Course.objects.filter(teacher = teacher)

context = {
    'teacher': teacher,
    'courses': courses
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM