【问题标题】:Django sum all related objects of a filtered QuerySetDjango 对过滤后的 QuerySet 的所有相关对象求和
【发布时间】:2017-04-19 10:15:03
【问题描述】:

我想在伪代码中做的是:

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

importer 的示例值:

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 节点(钱包)的所有“已导入”交易,以便将其提供给listtransactions RPC 端点的from 参数(一般来说,为了分页目的)。

【问题讨论】:

  • 那你的帖子标题为什么要“sum all”呢?

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


【解决方案1】:

这是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

【讨论】:

    【解决方案2】:

    你可以从Address开始过滤:

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

    【讨论】:

    • 好主意,不过我正在寻找 tx
    • 什么意思?
    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2016-01-15
    • 2010-09-20
    • 2019-02-14
    相关资源
    最近更新 更多