首页 > python > Django高效的一对多链查找

Django高效的一对多链查找 (Django Efficient One-to-Many Chain Lookup)

问题

我有以下数据结构:

class File(models.Model):
    dataset = models.ForeignKey(Dataset)

class Dataset(models.Model):
    mission = models.ForeignKey(Mission)

class Mission(models.Model):
    project = models.ForeignKey(Project)

class Project(models.Model):
    pass

我想有效地决定项目是否包含任何文件。从单个Project对象开始,如何获取所有相关文件的列表?

我理解project.mission_set.all()会让我得到第一层,但我不知道如何有效地链接查询。

解决方法

如果您想知道哪些Files实例与my_project实例相关,您可以按如下方式访问它:

my_project = Project.objects.create()

File.objects.filter(dataset__mission__project=my_project)

为了知道你可以做的数量:

File.objects.filter(dataset__mission__project=project).count()

问题

I have the below data structure:

class File(models.Model):
    dataset = models.ForeignKey(Dataset)

class Dataset(models.Model):
    mission = models.ForeignKey(Mission)

class Mission(models.Model):
    project = models.ForeignKey(Project)

class Project(models.Model):
    pass

I'd like to efficiently decide if a Project contains any files. Starting from a single Project object, how do I obtain a list of all the related files?

I understand project.mission_set.all() would get me the first layer, but I don't know how to efficiently chain the queries.

解决方法

If you want to know what Files instances are related to my_project instance you can access it as follows:

my_project = Project.objects.create()

File.objects.filter(dataset__mission__project=my_project)

In order to know the quantity you can do:

File.objects.filter(dataset__mission__project=project).count()
相似信息