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

时间:2017-04-19 10:15:03

标签: python django django-models orm json-rpc

我想在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()

导入器的示例值:

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节点(钱包)的事务,以便将其提供给from RPC端点的listtransactions参数(一般来说,出于分页目的)。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以从Address开始过滤:

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