1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to get data from another model in DetailView

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to get objects from two models using DetailView. First, I set 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'),
    ]


    Here are my models:

    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)


    and the detail view:

    class PostDetailView(DetailView):
    model = Post


    Now, in my template, I can use:

    {{ object.title }}

    To access my post information but, I need to get some info from the other tables, in this view. I know I have to overwrite the get_context_data method, but I don't know how.

    Continue reading...

Compartilhe esta Página