django 如何将多个模型添加到一个列表视图中?

wqsoz72f  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(110)

我需要能够显示信息,从多个模型在一个单一的列表视图,但没有一个线索如何去做这件事,任何帮助将是非常有帮助的...
here is my code for me views.py:

from django.shortcuts import render, redirect
from django.views.generic import ListView, DetailView
from . models import Post, Task
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


@method_decorator(login_required, name='dispatch')
class HomeView(ListView):
    template_name = 'home.html'
    model = Post


@method_decorator(login_required, name='dispatch')
class Task(ListView):
    model = Task
    template_name = 'tasks.html'

here is my code for me models.py:

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    type = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    link = models.CharField(max_length=255)
    auther = models.ForeignKey(User, on_delete=models.CASCADE)
    description = models.TextField()

    def __str__(self):
        return self.title + ' | ' + str(self.auther)

class Task(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    urgency = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self,):
        return str(self.user.username) + ' | ' + 'Tasks'

下面是我HTML:
一个二个一个一个
如果你需要更多关于我想要实现的目标的信息,或者需要看到任何其他代码片段,请告诉我:)

eimct9ow

eimct9ow1#

我想,TemplateView可能更适合你。如果你不打算使用分页,ListView不是你真正需要的。下面是你的代码应该看起来的样子:

@method_decorator(login_required, name='dispatch')
class HomeView(TemplateView):
    template_name = 'home.html'
    
    def get(self, request, *args, **kwargs):
        self.extra_context = {
            "posts": Post.objects.all(),
            "tasks": Task.objects.all(),
        }
        return self.render_to_response(self.extra_context)

因此,您必须更改模板中的标签,并将object_list分别替换为post和task。

{% for post in posts %}
{% for task in tasks %}

希望对你有帮助!

相关问题