我有一个由 django 构建的博客应用程序,如果有新评论,我想通知博主,所以这就是我所做的
class Blog(models.Model):
lastview = models.DateTimeField('self last view date')
class Comment(models.Model):
blog = models.ForeignKey(Blog)
timestamp = models.DateTimeField('comment date')
user_blog_list = Blog.Objects.filter(author = request.user)
user_blog_com = {}
for blog in user_blog_list:
user_blog_com [blog] =list(Comment.objects.filter(blog = blog ))
现在 user_blog_com
是字典的样子
{
(Blog: blogname1):[(Comment:comment1),(Comment:comment2)],
(Blog: blogname2):[(Comment:comment1),(Comment:comment2)],
}
接下来我需要将每条评论的时间戳与博客的 lastview 进行比较,以确定该评论是否被博主查看,但我不知道如何。
我要的是像这样的光盘
{
(Blog: blogname):[(Comment:unviewed_comment),(Comment:unviewed_comment)],
}
请帮忙!!!
我试试这个
user_blog_com = {}
for blog in user_blog_list:
user_blog_com [blog] =list(Comment.objects.filter(blog = blog ,timestamp > blog.lastview ))
get an error: non-keyword arg after keyword arg
最佳答案
我还没有测试过,但下面应该会为您提供每个博客的新评论列表。
from django.db.models import F
comments = Comment.objects.filter(
blog__author=request.user
).filter(
timestamp__gte=F('blog__lastview')
).select_related('blog').order_by('blog')
F() Expressions允许您逐行引用数据库中的值。除此之外,您只是要求所有新评论 timestamp__gte=blog__lastview
,当前用户是作者。我们使用 select_related
这样您就可以访问 blog
实例的详细信息而无需其他查询,并且使用 order_by('blog')
这样您得到了一些订单。
如果您必须在字典中包含此信息(我想知道为什么会这样......)那么您可以执行以下操作:
from collections import defaultdict
d = defaultdict(list)
for comment in comments:
d[comment.blog.name].append(comment)
比您尝试构建它的方式更具可读性和表现力。
关于python - 如何在 python 中过滤列表字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209113/