Как получить данные из другой модели в DetailView

Я пытаюсь получить объекты из двух моделей, используя 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 set queryset variable

class PostDetailView(DetailView):
  # model = Post
  queryset = {custom queryset}

#2 переопределить метод get_queryset

class PostDetailView(DetailView):
  # model = Post
  def get_queryset(self, **kwargs):
    return {custom queryset}

You can access related object data in the template without get_context_data. For example {{ object.comment.comment }} will render the comment text for the Post model object. Please note that object.comment refers to the Comment model object.

But if I understand the idea correctly, I would advise looking into ForeignKey instead of OneToOneField. Here's a good overview - OneToOneField() vs ForeignKey() in Django.

yeah, for comment it's the comment variable and for for tags it's also the comment variable

I didn't understand this exactly, so I interpreted it as bringing comments and tags related to Post.

It can be implemented through a query set without the need to use the get_context_data method suggested by the questioner.

views.py

from django.views.generic import DetailView

from .models import Post

# Create your views here.
from django.views.generic import DetailView

from .models import Post

# Create your views here.
class PostDetailView(DetailView):
  template_name = "posts/post-detail.html"
  context_object_name = "post"
  model = Post

As shown above, PostDetailView renders a post-detail.html template, and the Post object delivered from that template can be accessed with the value "post" which is the context_object_name.

post-detail.html

<html>
  <head>
    <title>{{ post.title }}</title>
  </head>

  <body>
    <h1>{{ post.title }}</h1>
    <div>{{ post.content }}</div>
    <div>{{ post.comment.comment }}</div>
    <div>{{ post.tags.comment }}</div>
  </body>
</html>

That's why you can access a single post delivered by PostDetailView when you use post as a template variable in a post-detail template.

And the comment and tags objects connected to the post can also be accessed directly from the post object.

  • post.conmment.(comment field)
  • post.tags.(tags field)

This approach is possible because You connected to OneToOneField. Please refer to this document for more reasons!

And I have one question.

If you connect the comments and tags to OneToOneField, you have one comment, tag per Post. Is this the expected part?

Вернуться на верх