1
0

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 5 years have passed since last update.

[django]ManyToManyField(中間モデル)の要素にテンプレートからアクセスする方法

Posted at

経緯

汎用詳細ビューでテンプレートから中間モデルのフィールドにアクセスする方法がわからなかったため、
調べたところ、良い方法が見つからなかったため。
django初心者につき、もっと良い方法があればご教示いただきたいです。

暫定解決方法

models.py
class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

カスタムフィルターを準備

extras.py
from django import template

register = template.Library()

@register.filter()
def get_relation_id(qs, group_id):
    return qs.filter(group=group_id).get().id

@register.filter()
def get_relation_invite_reason(qs, group_id):
    return qs.filter(group=group_id).get().invite_reason

フィルターを使用し、要素にアクセス

group_detail.html
{% for member in object.mermbers %}
<tr>
<td>{{ member.membership_set|get_relation_id:object.id }}</td>
<td>{{ member.membership_set|get_relation_invite_reason:object.id }}</td>
</tr>
{% endfor %}
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?