Django - 查询所有 table 中外键等于主 table 中所选记录的记录

Django - query the records in all tables that have the foreign key equal to the selected record in the main table

在 Django 中,我想查询所有具有外键 project = ProjectMain's chosen pk 的表中的记录。因此,如果我在 ProjectMain 中选择一条记录并且它是 pk=2,我还想要来自其他三个表的记录,其中外键 product=2.

表 Methods、Things 和 MoreStuff 可以有多个项目为 2 的记录。

这是表格:

class ProjectMain(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.CharField(max_length=60)
    product = models.ForeignKey(ProductType, on_delete=models.CASCADE)
    filler = models.CharField(max_length=100)


class Methods(models.Model):
    method_name = models.CharField(max_length=10)
    method_test = models.CharField(max_length=50, null=False)
    project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)


class Things(models.Model):
    thing1 = models.CharField(max_length=10)
    thing2 = models.CharField(max_length=50, null=False)
    project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)


class MoreStuff(models.Model):
    stuff1 = models.CharField(max_length=10)
    stuff2 = models.CharField(max_length=50, null=False)
    project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)

我一直在尝试 Django 查询集,但一无所获。请帮忙

您可以通过 related_name 属性 中定义的 ForeignKey.

访问它们
project_main = ProjectMain.objects.get(id=2)
methods = project_main.methods_set.all() # All the Methods related to the instance
things = project_main.things_set.all() # All the Methods related to the instance
more_stuffs = project_main.morestuff_set.all() # All the Methods related to the instance