【问题标题】:Django : No operator matches the given name and argument types. You might need to add explicit type castsDjango:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换
【发布时间】:2021-05-13 19:47:06
【问题描述】:

我在过滤我的 postgresql 上的数据时遇到了这个错误,它说错误来自这一行 .filter(bene_id='31452')。我一直在 Django 中使用两个表。我认为问题出在我的运营商 = 上,因为 id 是整数,但问题是我应该如何以及在该运营商中替换什么?

我尝试放置双 qoute、单 qoute 甚至没有像 .filter(bene_id="31452").filter(bene_id=31452).filter(bene_id='31452') 这样的元素。但似乎错误尚未解决。如果有人能弄清楚我做错了什么,那就太好了。提前非常感谢你

错误

LINE 1: ...2_benes_status" WHERE "b2_benes_status"."bene_id" = 31452  L...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need 
to add explicit type casts.

views.py

Testing = B2BenesStatus.objects.using('matchy_data').filter(bene_id='31452')

Models.py

class B2BenesStatus(models.Model):
    datetime = models.DateTimeField(blank=True, null=True)
    value = models.BooleanField(blank=True, null=True)
    remarks = models.TextField(blank=True, null=True)
    bene_id = models.IntegerField(blank=True, null=True)
    stat_cat_id = models.IntegerField(blank=True, null=True)
    updated_by_id = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'b2_benes_status'

Settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'payroll',
    'USER':'root',
    'PASSWORD':'',
    'HOST':'localhost',
    'PORT':'3306',

},
    'matchy_data': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'matchy_data',
    'USER':'postgres',
    'PASSWORD':'samplee',
    'HOST':'localhost',
    'PORT':'5432',
},}

【问题讨论】:

  • 将查找中的 id 更改为整数。 stackoverflow.com/questions/3739808/…
  • @PacketLoss 但在我的模型中它已经设置为 integerFiled bene_id = models.IntegerField(blank=True, null=True) ,您的意思是应该将其更改为 TextField 吗?
  • 我认为问题出在我的操作员= 上,因为 id 是整数,但问题是我应该如何以及在该操作员中替换什么?
  • ORM 查询正确。不要使用 qoutes,因为它是整数字段。我建议重试没有 qoutes 的代码。我没有使用过第二个数据库和 postgresql,所以如果没有任何工作(并且你有时间),你可以在默认数据库中尝试一个具有相同字段的测试模型并尝试这个 Testing = B2BenesStatus.objects.filter(bene_id=31452)跨度>

标签: python django


【解决方案1】:

假设bene_id 确实以整数形式存储在您现有的 SQL 数据库中(请仔细检查):

由于bene_idIntegerField.filter(bene_id='31452') 将失败,因为'31452' 是字符串类型。另外请注意,"' 在 Python 中没有根本区别。

您需要将int 类型传递给bene_id 参数,例如.filter(bene_id=31452)

您说您尝试不使用字符串分隔符但没有成功,但我怀疑后面还有另一个问题。

【讨论】:

  • 我刚刚发现错误是我想打印该查询Testing 。但它应该假设是打印的?我应该如何显示Testing 值?
  • 由于 QuerySets 是惰性的,它们不会立即被评估,而是当一些后续代码实际使用它们时。 print(Testing) 应该返回 __str__ 表示 B2BenesStatus 对象。
【解决方案2】:

测试 = B2BenesStatus.objects.using('matchy_data').filter(bene_id=int('31452'))

否则

测试 = B2BenesStatus.objects.filter(bene_id=int('31452'))

试试这个并检查它是否有效:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2020-08-26
    • 2011-04-13
    • 2021-02-05
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多