0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoでForeign Keyを逆に辿りたい

Last updated at Posted at 2021-03-27

DjangoでForeign Keyを逆にたどるために色々調べたのでメモ。
間違っているとことかあれば教えてほしい。

例えば、病院に勤務する医者のモデルを考える。

class Hospital(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name


class Users(models.Model):
    name = models.CharField(max_length=10)
    hospital = models.ForeignKey(
        Hospital, on_delete=PROTECT, null=True, blank=True, )

    def __str__(self):
        return self.name

ユーザに対し、1つの病院を紐付けている。
医師モデルの中に、所属している病院を登録しているイメージだ。

ではここから、ある病院に所属している医師のリスト を取得したい

その前に一度 views.pyを見てみよう。以下のように書いた。

from django.views import generic
from .models import Users, Hospital
from django.shortcuts import get_object_or_404


class HospitalView(generic.ListView):
    model = Hospital


class DetailView(generic.DetailView):
    model = Hospital
    template_name = 'testapp/detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  # はじめに継承元のメソッドを呼び出す
        hospital = Hospital.objects.get(name=context["hospital"])
        context["users"] = hospital.users_set.all()
        return context

以下の様にすれば、データを受け渡したテンプレート内で users としてその病院に所属している医師のリストを取得することができた。

ポイントは、

hospital = Hospital.objects.get(name=context["hospital"])
# と
hospital.users_set.all()
# の部分だ。

hogehoge = .objects.get(name = 子の名前)

hogehoge.子モデル名_set.all()

という具合になった。

ちなみにテンプレートは以下のようにすれば良い。

{{hospital}}

<ul>
    {{% for user in users %}
    <li>{{ user }}</li>
    {% endfor %}}
</ul>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?