Cra*_*oli 13 django join concatenation django-queryset
我目前有两种不同的型号.
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)
Run Code Online (Sandbox Code Playgroud)
我在视图中创建一个报告并收到以下错误:合并'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
...
Run Code Online (Sandbox Code Playgroud)
如果我试着让它们完全相同来测试例如
def report(request):
ledger = GeneralLedger.objects.values('memo').annotate(total=Sum('amount'))
journal = Journal.objects.values('memo').annotate(total=Sum('amount'))
report = ledger & journal
...
Run Code Online (Sandbox Code Playgroud)
我收到此错误:无法在两个不同的基本模型上组合查询.
有谁知道如何实现这一目标?
Lak*_*sad 25
from itertools import chain
report = chain(ledger, journal)
Run Code Online (Sandbox Code Playgroud)
Itertools赢了!
如果你想做一个Union,你应该把它们转换querysets
成python set
对象.
如果可以正确过滤查询集本身,那么你应该真的这样做!
小智 5
from itertools import chain
report = list(chain(ledger, journal))
Run Code Online (Sandbox Code Playgroud)
注意:您需要将生成的对象转换为一个列表,以便 Django 能够处理它。
归档时间: |
|
查看次数: |
12915 次 |
最近记录: |