我正在尝试使用
DetailView
从两个模型中获取对象。首先,我设置 urls.py:
from django.urls import path
from . views import RetiroListView, RetiroDetailView
from . import views
urlpatterns = [
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/', views.post, name='post-post'),
]
这是我的模型:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Comment(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True)
comment=models.CharField(max_length=100)
class Tags(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True)
comment=models.CharField(max_length=100)
和详细视图:
class PostDetailView(DetailView):
model = Post
现在,在我的模板中,我可以使用:
{{ object.title }}
要访问我的帖子信息,但是,我需要在此视图中从其他表中获取一些信息。我知道我必须覆盖
get_context_data
方法,但我不知道如何。
#1 设置查询集变量
class PostDetailView(DetailView):
# model = Post
queryset = {custom queryset}
#2 重写 get_queryset 方法
class PostDetailView(DetailView):
# model = Post
def get_queryset(self, **kwargs):
return {custom queryset}