Django 在尝试过滤查询集时无法将整数类型转换为smallint

问题描述 投票:0回答:1

我有一个

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
的替代品。
或者这是/应该进行过滤的方式吗?我以前没有遇到过这个问题,通过搜索我没有找到任何看起来相同的东西(迁移或其他类型转换时出现一些错误,但没有像这样的)。
感觉确实是一个简单的问题,但我找不到解决方法。

django django-models filtering django-queryset
1个回答
0
投票

当您查询 ArrayField 时,您需要提供一个值数组,您不能简单地传递值本身,因此在这种情况下,您传递的变量“genre”应该是一个值数组,例如, [1] 或 [1, 2, 3] 表示多个值。它应该可以解决你的问题。

ArrayField中查询的文档供参考。

© www.soinside.com 2019 - 2024. All rights reserved.