Django queryset values_list是否返回列表对象? [英] Does Django queryset values_list return a list object?

查看:285
本文介绍了Django queryset values_list是否返回列表对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用,用户可以在其中发布照片,并在照片下方发表其他评论。



留下评论时,我需要通知:


  1. 其他人谁在此线程中撰写

  2. 照片的所有者,以防不属于(1)

对于(1),我这样做:

  #I切成25分,因为我任意认为超出此范围的任何人不相关的。 
all_commenter_ids = PhotoComment.objects.filter(which_photo = which_photo).order_by('-id')。values_list('submitted_by',flat = True)[:25]

接下来,对于(2),我尝试:

  all_relevant_ids = all_commenter_ids.append(which_photo.owner_id)
all_relevant_ids = list(set(all_relevant_ids))

我最终得到一个错误:


'ValuesListQuerySet'对象没有属性'append'


我发现这很奇怪,因为我正在提取 values_list



不是列表对象,在这种情况下,属性不应添加场景?请解释问题所在,并提出其他建议。

解决方案

values_list 方法返回 ValuesListQuerySet 。这意味着它具有查询集的优点。例如,它是惰性的,因此切片时仅从数据库中获取前25个元素。



要将其转换为列表,请使用 list()

  all_commenter_ids = PhotoComment.objects.filter(which_photo = which_photo).order_by ('-id')。values_list('submitted_by',flat = True)[:25] 
all_commenter_ids = list(all_commenter_ids)

您也许可以从 User 模型启动查询集,而不必使用 values_list 。您尚未显示模型,因此下面的代码是一个猜测:



from django.db.models import Q

评论者= User.objects.filter(Q(id = which_photo.owner_id)| Q(photocomment = which_photo))


I have a Django app where users post photos, and other leave comments under the photos.

When a comment is left, I need to notify:

  1. Everyone else who wrote in this thread
  2. The owner of the photo, in case they're not included in (1)

For (1), I do:

#I slice by 25 because I arbitrarily deem anyone beyond that irrelevant. 
all_commenter_ids = PhotoComment.objects.filter(which_photo=which_photo).order_by('-id').values_list('submitted_by', flat=True)[:25]

Next, for (2), I try:

all_relevant_ids = all_commenter_ids.append(which_photo.owner_id)
all_relevant_ids = list(set(all_relevant_ids))

I end up with an error:

'ValuesListQuerySet' object has no attribute 'append'

I find this strange, because I'm extracting a values_list.

Isn't that a list object, and in that case, shouldn't the attribute append work in this scenario? Please explain what's wrong, and suggest alternatives.

解决方案

The values_list method returns a ValuesListQuerySet. This means it has the advantages of a queryset. For example it is lazy, so you only fetch the first 25 elements from the database when you slice it.

To convert it to a list, use list().

all_commenter_ids = PhotoComment.objects.filter(which_photo=which_photo).order_by('-id').values_list('submitted_by', flat=True)[:25]
all_commenter_ids = list(all_commenter_ids)

You might be able to start the queryset from your User model instead of using values_list. You haven't shown your models, so the following code is a guess:

from django.db.models import Q

commenters = User.objects.filter(Q(id=which_photo.owner_id)|Q(photocomment=which_photo))

这篇关于Django queryset values_list是否返回列表对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆