首页 > 解决方案 > 如何使用 asyncpg (python) 在 postgresql 表中插入具有 ManyToMany 关系的列?

问题描述

我想在一开始就说明这是一个混合 python 和 postgresql 的问题。我目前正在使用 tortoise-orm 为我处理所有与 sql 相关的东西,但今天我在插入 JSONB 字段时遇到了困难。这是我的桌子:

class PointsInfo(models.Model):
    class Meta:
        table = "pt_info"

    id = fields.BigIntField(pk=True, index=True)
    guild_id = fields.BigIntField(index=True)
    kill_points = fields.IntField(default=1)
    posi_points = fields.JSONField(default=dict)
    default_format = fields.IntField(default=1)
    data: fields.ManyToManyRelation["PointsTable"] = fields.ManyToManyField("models.PointsTable", index=True)


class PointsTable(models.Model):
    class Meta:
        table = "pt_data"

    id = fields.BigIntField(pk=True, index=True)
    points_table = fields.JSONField()
    created_by = fields.DatetimeField()
    created_at = fields.DatetimeField(auto_now=True, index=True)
    edited_at = fields.DatetimeField(null=True)
    channel_id = fields.BigIntField(null=True)
    message_id = fields.BigIntField(null=True)

我想在pt_data表中插入一行,然后将该行添加到表中的datapt_info

_dict = {'quotient': [1, 20, 20, 40], 'butterfly': [2, 14, 14, 28], '4pandas': [3, 10, 8, 18], 'kite': [4, 10, 5, 15]}

table = await PointsTable.create(points_table=_dict, created_by= 123456789)
points= await PointsInfo.get(id=3)
await points.data.add(table)

但在执行此操作时出现错误:

File "/home/deadshot/softs/softs/total-quotient/Quotient-Bot/.venv/lib/python3.8/site-packages/tortoise/models.py", line 655, in __init__
    for key in meta.fields.difference(self._set_kwargs(kwargs)):
  File "/home/deadshot/softs/softs/total-quotient/Quotient-Bot/.venv/lib/python3.8/site-packages/tortoise/models.py", line 682, in _set_kwargs
    setattr(self, key, field_object.to_python_value(value))
OSError: [Errno 75] Value too large for defined data type

idk为什么python无法解析那个dict

所以我想用原始 SQL 来做这个,因为我用 tortoise-orm 做这个,我对原始 SQL 没有太多经验,我知道基础知识,但这对我来说是先进的。

我应该在这里做什么?你能帮我写下我想在这里实现的原始 SQL 查询吗?

谢谢。

标签: pythonpython-3.xpostgresqlasyncpgtortoise-orm

解决方案


推荐阅读