DjangoのORMを使用したときの参照テーブルへの条件指定

FKで参照しているテーブルに関しては、参照している先から filter にて参照が可能。

仮に、下記のようなモデルがあったとする。

from django.db import models

class test_grand_parents(models.Model):
    name models.CharField(max_length=50);
    created_at = models.DateTimeField(auto_now_add = True);
    updated_at = models.DateTimeField(auto_now = True);

class test_parents(models.Model):
    grand_parent = models.ForeignKey(test_parents, on_delete=models.DO_NOTHING);
    name models.CharField(max_length=50);
    created_at = models.DateTimeField(auto_now_add = True);
    updated_at = models.DateTimeField(auto_now = True);

class test_children(models.Model):
    parent = models.ForeignKey(test_parents, on_delete=models.DO_NOTHING);
    name models.CharField(max_length=50);
    created_at = models.DateTimeField(auto_now_add = True);
    updated_at = models.DateTimeField(auto_now = True);

test_grand_parentstest_parentstest_children はそれぞれ参照関係にある。

この時に、 test_children から test_grand_parents の要素を指定して、検索することができる。

下記はその一例

import models

grand_parent_id = 1;
child_list = test_children.objects.all().filter(parent__grand_parent=grand_parent_id);

この場合は、 grand_parent のIDが1の test_children をリストで取得する。