如何在视图中访问pk(Django)

时间:2017-04-19 14:53:14

标签: python django views display

我正在Django中编写一个小型聊天程序,但在进一步的问题上有问题。

以下是代码:

models.py

df1 = testDf.groupby(['Date', 'Scenario'])['Value'].apply(lambda x: list(x)).reset_index()\
            .pivot(index='Date', columns='Scenario', values='Value').fillna('')

# Scenario         Buy   Sell
# Date                       
# 20170323       [400]       
# 20170324              [400]
# 20170325  [400, 401]       

# Scenario         Buy   Sell
# Date                       
# 20170321  [400, 401]       
# 20170323       [400]       
# 20170324              [400]

urls.py

from django.db import models
from datetime import datetime
from django.utils import timezone

class Chat(models.Model):
    chatname = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.chatname

class Comment(models.Model):
    chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
    commenter = models.CharField(max_length=30)
    comment = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.comment

views.py

from django.conf.urls import url
from . import views
from django.views.generic import ListView
from chat.views import CommentList

app_name = 'chats'
urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentList.as_view(), name='comments'),
]

我的comment_list.html

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login

from django.views import generic
from .models import Chat, Comment

def index(request):
    username = None 
    if request.user.is_authenticated():
        username = request.user.username

    chats = Chat.objects.all()[:10]

    context = {
        'chats':chats
    }
    return render(request, 'chat/index.html', context)

class CommentList(generic.ListView):
    queryset = Comment.objects.filter(chat_id=1)
    context_object_name = 'comments'

我的数据库结构包含以下两个模型:聊天和评论。每个聊天(房间)应该有自己的评论。我使用'models.ForeignKey'来过滤每个聊天(房间)的评论。在我的index.html中,我列出了所有的聊天记录,每个聊天记录都有一个指向/ comments /部分的超链接。

在我的views.py中我有这一行:'queryset = Comment.objects.filter(chat_id = 1)' Chat_id是注释sql表中的列,因为它现在只显示属于pk = 1的聊天的注释。如何自动访问聊天以获取不同的网址/评论/ 1 / /评论/ 2 /等等。?

希望解释清楚。对不起初学者,我可以尝试进一步解释它是否没有多大意义。

最佳, 费边

2 个答案:

答案 0 :(得分:1)

您可以使用普通视图代替CommentList

def comments_index(request, chatid):
    return render(request, 'xxx/comment_list.html', {
        'comments': Comment.objects.filter(chat_id=chatid)
    })

在网址中:

url(r'^comments/(?P<chatid>[0-9]+)/$', views.comments_index, name='comments'),

答案 1 :(得分:1)

您应该定义get_queryset方法,而不是独立的queryset属性。

def get_queryset(self, *args, **kwargs):
    return Comment.objects.filter(chat_id=self.kwargs['pk'])