So fügen Sie ein Diktat zu QuerySet hinzu
Posted: 03 Jan 2025, 11:50
Ich habe ein Ergebnis aus der DB, das ich mit einer Zeile anreichern möchte. Ein Abfragesatz ist ein Diktat, oder? Also habe ich ein neues Diktat erstellt und wollte diese beiden zusammenführen. Aber mir wurde gesagt, dass man ein Diktat und ein QuerySet nicht zusammenführen kann. Wie geht das?
Die Abfrage
Ich überprüfe, ob das Ergebnis das aktuelle Jahr enthält. Wenn nicht, möchte ich es mit 0 hinzufügen
Die Abfrage
Code: Select all
years = (Transactions.objects
.annotate(year=TruncYear('timestamp'))
.values('year')
.order_by('-year')
.annotate(total=Sum('amount'))
.annotate(earnings=Sum('amount', filter=Q(amount__gt=0)))
.annotate(spent=Sum('amount', filter=Q(amount__lt=0)))
.annotate(count=Count('id'))
.values('year', 'total', 'count', 'earnings', 'spent'))