1

私は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_comdictは次のように見えます

{
  (Blog: blogname1):[(Comment:comment1),(Comment:comment2)],
  (Blog: blogname2):[(Comment:comment1),(Comment:comment2)],
}

次に、各コメントのタイムスタンプをブログのラストビューと比較して、コメントがブロガーによって閲覧されているかどうかを確認する必要がありますが、方法がわかりません。

私が欲しいのはディスクのようなものです

{
  (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
4

2 に答える 2

3

私はまだテストしていませんが、以下はすべてのブログの新しいコメントのリストです。

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() 式を使用すると、データベース内の値を行単位で参照できます。それ以外はtimestamp__gte=blog__lastview、現在のユーザーが作成者であるすべての新しいコメントを求めているだけです。を使用して、別のクエリなしでインスタンスselect_relatedの詳細にアクセスできるようにし、順序付けを行います。blogorder_by('blog')

この情報を辞書に載せる必要がある場合 (なぜそうなるのか不思議です..)、次のようにします。

from collections import defaultdict
d = defaultdict(list)
for comment in comments:
    d[comment.blog.name].append(comment)

構築しようとしている方法よりもはるかに読みやすく表現力があります。

于 2013-01-08T06:30:22.247 に答える
1

これを試して

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

これはあなたを助けるかもしれません。

于 2013-01-08T06:24:44.053 に答える