Django queryset values_list是否返回列表对象?

时间:2021-08-28 21:27:10

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

我有一个Django应用程序,用户发布照片,其他留下评论照片下。

When a comment is left, I need to notify:

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

  1. Everyone else who wrote in this thread
  2. 在这个帖子中写道的其他人
  3. The owner of the photo, in case they're not included in (1)
  4. 照片的所有者,如果他们不包括在(1)

For (1), I do:

对于(1),我这样做:

#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:

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

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'

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

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

我发现这很奇怪,因为我正在提取一个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.

这不是一个列表对象,在这种情况下,属性追加不应该在这种情况下工作吗?请解释什么是错的,并提出替代方案。

1 个解决方案

#1


19  

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.

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

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

要将其转换为列表,请使用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:

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

from django.db.models import Q

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

#1


19  

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.

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

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

要将其转换为列表,请使用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:

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

from django.db.models import Q

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