Django 查询集,在另一个查询中使用查询集?
Django queryset, using a queryset in another query?
假设我在存储 when-user-read-something
的地方有 ReadRecord
。 (某物是通用外键)
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])
您不能在一个查询中真正做到这一点,因为您使用的是通用外键而不是真正的外键,而 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)
假设我在存储 when-user-read-something
的地方有 ReadRecord
。 (某物是通用外键)
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])
您不能在一个查询中真正做到这一点,因为您使用的是通用外键而不是真正的外键,而 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)