Django queryset,在另一个查询中使用查询集?

时间:2015-08-21 07:56:50

标签: django django-queryset

假设我ReadRecord存储了when-user-read-something。 (某些东西是通用的外键)

ReadRecord:
  object = GFK(object_id, content_type)
  user
  timestamp

我有一个博客模型

Blog:
  modified_at

我想知道一组博客中是否有一个博客,其last_modified_at大于时间戳。 (有一个用户需要阅读的博客)

#First I get all read_records for a user for the blog set. 

read_records = ReadRecord.objects.filter(
     content_type=ctype, object_id__in=object_ids, user=user)

# see if there's any new blog a user need to read
for blog in the_blog_set:

   if not read_records.filter(object_id=blog.id).exists():
       return True
   if read_records.filter(object_id=blog.id)[0].time_stamp < blog.modifed_at:
       return True

return False

想知道是否有更好的查询方式?

这样的东西
blog_set.filter(id=T(read_records[object_id] & modified_at > T(read_records[time_stamp]) 

1 个答案:

答案 0 :(得分:0)

您无法在一个查询中执行此操作,因为您使用的是通用外键而不是真正的外键,而Django无法将其转换为JOIN。但你可以做的是使用prefetch_related一次性获取博客和记录,然后迭代。

read_records = ReadRecord.objects.filter(
         content_type=ctype, object_id__in=object_ids, user=user
    ).prefetch_related('object')
blogs_to_read = []
for record in read_records:
    if record.timestamp < record.object.modified_at:
        blogs_to_read.append(object)