python - 如何在 python 中过滤列表字典?

标签 python django list dictionary

我有一个由 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/

相关文章:

python - 将许多 txt/csv 文件编译成单个数据框,并将文件名添加为列

c# - 从列表中填充组合框

python - 使用别名导入模块

python - Django:在页面中列出每个类别的产品

java - 如何使用通配符作为类型对空列表使用react?

javascript - 寻求帮助以使 npm/pdfjs-dist 与 Webpack 和 Django 一起工作

Django MPTT Postgres 更新查询运行缓慢

python - 张量到变量的切片赋值

python - Boto分配弹性IP

python - 如何使用 Python 多处理队列访问 GPU(通过 PyOpenCL)?