python - Django 对过滤后的查询集的所有相关对象求和

标签 python django django-models orm json-rpc

我想在伪代码中做的是:

def import_transaction_deposit_crypto(Importer):
    logger = get_nexchange_logger(__name__, True, True)
    existent_addresses = Address.objects.filter(
        currency__is_crypto=True,
        type=Address.DEPOSIT,
        currency__wallet__in=Importer.RELATED_NODES

    ).tx_to_set.count()

进口商的值(value)示例:

class LitecoinTxImporter:
    RELATED_NODES = 'ltc_rpc_1'

tx_to 是一个 related_field(反向关系):

class Address(BtcBase, SoftDeletableModel):
    address_to = models.ForeignKey('core.Address',
                                   related_name='txs_to')

这个想法是对属于特定 RPC 节点(钱包)的所有“已导入”交易进行计数,以便将其提供给 RPC 节点的 from 参数listtransactions RPC 端点(一般来说,用于分页目的)。

最佳答案

这是documented here有一个完美匹配的例子:

# Build an annotated queryset
>>> from django.db.models import Count
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
<Book: The Definitive Guide to Django>
>>> q[0].authors__count
2

关于python - Django 对过滤后的查询集的所有相关对象求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492758/

相关文章:

python - 是否有一个版本的 __file__ 在函数中使用时会获取使用该库的文件的名称?

python - Boost Python用默认参数包装静态成员函数重载

python - 在 Mac 上的终端中运行 Python 3.6?

python - 系列列表到数据框

python - 使用适当的十进制数据类型将 django 中的模型序列化为 json

python - 模块未定义属性/类

python - 如何使用 AJAX 使用相同的 html 模板(使用 Python 和 Django)创建和编辑新帖子?

python - 防止 Django 级联删除父类(super class)

django - 比较在 Django 中存储为字符串的日期

Django ArrayField 过滤包含匹配