1

如何在不AssertionError出错的情况下将多个 tinyDB(基于文档的数据库)数据库添加在一起?我试图在这个例子中添加 12 个 tinyDB 数据库。

文件结构:
在此处输入图像描述

每个编号的文件看起来像这样:

{
    "_default": {
        "1": {
            "Strategy": "MAShift",
            "Symbol": "AAVE/USD",
            "Timeframes": [
                "30T"
            ],
            "Parameters": {
                "atr": 14,
                "sma": 5,
                "longLine": 3,
                "shortLine": 5,
                "slMultipier": 12,
                "leverage": 1
            },
            "Start": "2020-10-13 12:00:00",
            "End": "2021-04-26 11:30:00",
            "Duration (days)": 194,
            "Equity Start [$]": 10000,
            "Equity Final [$]": 90470.5732,
            "Return [%]": 804.71,
            "Max. Drawdown [%]": -28.1,
            "Win rate [%]": 69.12,
            "Total trades": 570,
            "Avg. trade [%]": 0.43,
            "Avg. winning trade [%]": 1.88,
            "Avg. losing trade [%]": -2.81
        }, ...
    }
}

我的代码:

from tinydb import TinyDB

resultsTotalDb = TinyDB(f'db/backtestingResultsTotal.json')

for i in range(12):
    resultsDb = TinyDB(f'db/backtestingResults{i}.json')
    for result in resultsDb.all():
        resultsTotalDb.insert(result)

错误:

AssertionError: doc_id 1 already exists

4

1 回答 1

2

您可以根据数据库计数器重新计算新的文档 ID:

from tinydb import TinyDB
from tinydb.table import Document

# ...

for i in range(12):
    resultsDb = TinyDB(f"db/backtestingResults{i}.json")

    for result in resultsDb.all():
        new_id = i * 100000000 + result.doc_id
        resultsTotalDb.insert(Document(result, doc_id=new_id))
于 2021-04-26T15:35:06.940 回答