django query returns error: expected str instance, ValuesListQuerySet found

django query returns error: expected str instance, ValuesListQuerySet found

我有一个脚本,它一个一个地从 list_of_animals 中获取值并用它们执行一些操作。
它的工作原理是这样的:

list_of_animals = ["Dog", "Cat", "Fish"]
for x in list_of_animals:
...

代码循环遍历此列表,一次一只动物并结束。

现在,对于下一步,我有一个这样的模型:

class MyModel(models.Model):
animal = models.CharField(max_length=25, unique=True, error_messages=
{'unique':"This animal is added already."})
timestamp = models.DateTimeField()

...以及 SQLite 数据库中的更多动物。所以我尝试用查询替换手动创建的 list_of_animals

我试过这样更改 list_of_animals:

list_of_animals = [MyModel.objects.values_list('title', flat=True)]

但我收到 错误

expected str instance, ValuesListQuerySet found

其实我也尝试了很多其他的方法,但是都没有成功。
你能帮我找到一种方法来用同样工作方式的查询替换手动创建的列表吗?

谢谢!

尝试:

list_of_animals = list(MyModel.objects.values_list('title', flat=True))

来自the docs

Note that this method returns a ValuesListQuerySet. This class behaves like a list. Most of the time this is enough, but if you require an actual Python list object, you can simply call list() on it, which will evaluate the queryset.

而不是list_of_animals = [MyModel.objects.values_list('title', flat=True)],而是

list_of_animals = MyModel.objects.values_list('title', flat=True)

如果您将 flat=True 与单个字段列表一起使用,MyModel 默认将 return 一个可迭代列表,如 documentation here:

中所述

If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples. An example should make the difference clearer:

>>> Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]

>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]