如何在Python中过滤字典列表?

2024-10-03 06:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

^{pr2}$

接下来,我需要将每条评论的时间戳与blog的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

Tags: commodelmodelscomment评论blog作者filter
2条回答

我还没有测试过,但是下面的内容应该会给你每个博客的新评论列表。在

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,其中当前用户是作者。{{cd3>你可以使用另一个实例,而不需要访问cd3}。在

如果您必须在字典中包含这些信息(我想知道为什么会是这样…),那么您可以执行以下操作:

^{pr2}$

比你试图构建它的方式更具可读性和表达力。在

试试这个

ret_dict = {}
for k, v in user_blog_com.items():
    # Check comments timestamp is smaller than lastview.
    ret_dict[k] = [x for x in v if x.timestamp <= k.lastview]

print ret_dict

这可能对你有帮助。在

相关问题 更多 >