我有这个型号:
class Donation(models.Model):
amount = models.IntegerField()
receipt = models.CharField(max_length=40, blank=True)
donation_date = models.DateTimeField()
donator = models.ForeignKey(User, related_name='donation_donator', blank=True, null=True, on_delete=models.SET_NULL)
validation_date = models.DateTimeField(blank=True, null=True)
然后是这个观点:
def report(request, month=None):
datafilter = Q()
datafilter = datafilter & Q(donation_date__month=month)
top_donors_month = Donation.objects.values('donator').annotate(Sum('amount')).order_by('-amount__sum').filter(datafilter)
top_donors_all = Donation.objects.values('donator').annotate(Sum('amount')).order_by('-amount__sum')
基本上它会返回donator-total_amount_donated关系列表。但查询返回一个像这样的字典:
[{'donator' : 3, 'amount_sum' : 5200}, {'donator' : 2, 'amount_sum' : 1200}, {.....}]
其中3,2,1 ..等是捐赠者pks。我怎样才能获得3的名字?
e.g。
[{'donator' : user1, 'amount_sum' : 5200}, {'donator' : user2, 'amount_sum' : 1200}, {.....}]
答案 0 :(得分:0)
而不是捐赠者,你必须获得值donator__first_name。
尝试以下,
top_donors_month = Donation.objects.values('donator__first_name').annotate(Sum('amount')).order_by('-amount__sum').filter(datafilter)
top_donors_all = Donation.objects.values('donator__first_name').annotate(Sum('amount')).order_by('-amount__sum')