简体   繁体   English

Django对过滤后的QuerySet的所有相关对象求和

[英]Django sum all related objects of a filtered QuerySet

What I would like to do in psuedo code is: 我想在psuedo代码中做的是:

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()

Example value of importer: 导入器的示例值:

class LitecoinTxImporter:
    RELATED_NODES = 'ltc_rpc_1'

tx_to is a related_field (reverse relation): tx_totx_to (反向关系):

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

The idea is to count all 'already imported' transactions that belong to a specific RPC node (wallet), in order to feed it to the from parameter of the listtransactions RPC endpoint (generally speaking, for pagination purposes). 我们的想法是计算属于特定 RPC节点(钱包)的所有“已导入”事务,以便将其提供给listtransactions RPC端点的from参数(一般来说,出于分页目的)。

This is documented here with a perfectly matching example: 这里记录了一个完美匹配的例子:

# 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

您可以从Address开始过滤:

Adress.objects.filter(address_to__curency__is_crpyto=True, ...).count()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM