我有一个
IntegerChoices
Genre
:
from django.db import models
# ...
class Genre(models.IntegerChoices):
fantasy = 0,
scifi = 1,
real = 2,
#...
以及使用
book
的 ArrayField
和 PositiveSmallIntegerField
作为选择的 Genre
模型:
from django.contrib.postgre.fields import ArrayField
#...
class Book(models.Model):
#...
genres = ArrayField(models.PositiveSmallIntegerField(choices=Genre.choices), null=True, blank=True))
#...
当我尝试使用
genres
选项中的值按 Genre
字段进行过滤时,我收到一条错误,指出 Django(或 psycopg2)无法将整数转换为smallint:
# traceback
psycopg2.errors.CannotCoerce: cannot cast type integer to smallint[]
LINE 1: ..."book" WHERE "book"."genres" @> 1::smallint...
^
The above exception was the direct cause of the following exception:
# traceback
django.db.utils.ProgrammingError: cannot cast type integer to smallint[]
LINE 1: ..."book" WHERE "book"."genres" @> 1::smallint...
^
所有这些过滤尝试都会触发上述错误:
genre = Genre.scifi
print(genre) # >>> 1
Book.objects.filter(genres__contains=genre) # error
Book.objects.filter(genres=genre) # error
但是,如果我尝试创建一个具有该类型的
book
实例,一切都会正常。
book = Book.objects.create(
#...
genres=[genre]
) # no error
print(book.genres) # >>> [1]
问题是
PositiveSmallIntegerField
吗?我找不到任何“SmallIntegerChoices”作为 IntegerChoices
的替代品。当您查询 ArrayField 时,您需要提供一个值数组,您不能简单地传递值本身,因此在这种情况下,您传递的变量“genre”应该是一个值数组,例如, [1] 或 [1, 2, 3] 表示多个值。它应该可以解决你的问题。
ArrayField中查询的文档供参考。