15
16

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のListviewで複数モデルのデータを取り出す方法

Last updated at Posted at 2020-12-05

はじめに

目標はブログアプリでトップページに投稿とタグを一覧表示させる。
そのためDjangoの汎用クラスviewであるList viewを使い、postモデルとtagモデルの2つのモデルのデータを取り出したい。

やり方

モデルの全体像。TagモデルとPostモデルが多対多の関係で定義されている。

/model.py

~
class Tag(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = MarkdownxField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    tags = models.ManyToManyField(Tag)
~

Djangoの汎用viewであるgenericから、Listviewを使って1つめのモデルであるpostモデルを取り出す。2つめからはget_context_data関数を継承して上書きするかたちにする。

/view.py

~
from .models import Post, Comment, Tag
from django.views.generic import ListView, DetailView

class PostList(ListView):
    context_object_name = 'post_list'
    queryset = Post.objects.order_by('-created_date')
    model = Post
    paginate_by = 7

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['tag_list'] = Tag.objects.all
        return context
~

テンプレート側では、context['tag_list']に格納した情報をfor文で取り出し表示していく

/テンプレート.html

~
        <div class="text">
          <ul>
            {% for tag in tag_list %}
            <li>{{ tag.name }}</li>
            {% endfor %}
          </ul>
        </div>

~

参考文献

https://stackoverrun.com/ja/q/10579173
https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data

15
16
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
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?