【问题标题】:Join Multiple Querysets From Different Base Models Django加入来自不同基本模型 Django 的多个查询集
【发布时间】:2011-10-07 14:52:08
【问题描述】:

我目前有两种不同的型号。

class Journal(models.Model):
    date = models.DateField()
    from_account = models.ForeignKey(Account,related_name='transferred_from')
    to_account = models.ForeignKey(Account,related_name='transferred_to')
    amount = models.DecimalField(max_digits=8, decimal_places=2)
    memo = models.CharField(max_length=100,null=True,blank=True)

class Ledger(models.Model):
    date = models.DateField()
    bank_account = models.ForeignKey(EquityAccount,related_name='paid_from')
    account = models.ForeignKey(Account)
    amount = models.DecimalField(max_digits=8, decimal_places=2)
    name = models.ForeignKey(Party)
    memo = models.CharField(max_length=100,null=True,blank=True)

我正在视图中创建报告并收到以下错误: 合并“ValuesQuerySet”类在每种情况下都必须涉及相同的值。

我要做的只是提取常见的字段,以便我可以将它们连接起来,例如

def report(request):

    ledger = GeneralLedger.objects.values('account').annotate(total=Sum('amount'))
    journal = Journal.objects.values('from_account').annotate(total=Sum('amount'))
    report = ledger & journal
...

如果我尝试使它们完全相同以进行测试,例如

def report(request):

    ledger = GeneralLedger.objects.values('memo').annotate(total=Sum('amount'))
    journal = Journal.objects.values('memo').annotate(total=Sum('amount'))
    report = ledger & journal
...

我收到此错误: 无法在两个不同的基本模型上组合查询。

有谁知道如何做到这一点?

【问题讨论】:

    标签: django join concatenation django-queryset


    【解决方案1】:
    from itertools import chain
    report = chain(ledger, journal)
    

    Itertools 赢了!

    如果你想做一个 Union,你应该将这些 querysets 转换成 python set 对象。

    如果可以正确过滤查询集本身,那么您真的应该这样做!

    【讨论】:

    • 我得到这个:AttributeError: 'itertools.chain' object has no attribute 'model'
    【解决方案2】:

    使用itertools.chain:

    from itertools import chain
    report = list(chain(ledger, journal))
    

    注意:您需要将生成的对象转换为列表,以便 Django 能够处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2018-06-27
      • 2018-04-24
      • 2019-04-14
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多