使用ForeignKey通过链接模型进行排序

时间:2019-07-09 10:42:02

标签: django django-models django-views

我需要通过Credit的关联模型对CreditPayment记录进行排序。

models.py

class Credit(models.Model):
    hot = models.BooleanField(default=False)


class CreditPayment(models.Model):
    credit = models.ForeignKey(Credit)
    period_to = models.PositiveIntegerField()
    rate = models.DecimalField(max_digits=7, decimal_places=2)

views.py

credits = credits.filter(hot=False).distinct().order_by(...)

输入数据示例:

Credit #1:
CreditPayment #1:
period_to = 12
rate = 10

CreditPayment #2:      (minimal)
period_to = 10
rate = 8

CreditPayment #3:      
period_to = 9
rate = 10

Credit #2:
CreditPayment #1:        (minimal)
period_to = 6
rate = 20

CreditPayment #2:
period_to = 9
rate = 20

Credit #3:
CreditPayment #1:
period_to = 12
rate = 8

CreditPayment #2:
period_to = 9
rate = 11

CreditPayment #3:       (minimal)
period_to = 9
rate = 8

结果,样本减少为:

Credit #1:    
CreditPayment #2:
period_to = 10
rate = 8

Credit #2:
CreditPayment #1:
period_to = 6
rate = 20

Credit #3:
CreditPayment #3:
period_to = 9
rate = 8

结果:

信用#3->信用#1->信用#2

如您所见,首先为每个CreditPayment选择了最低Credit(在 views.py 中的credits)。然后,根据这些最小值CreditPayment,对所有Credit进行排序。如果两个条目的费率相等,则用period to比较这些条目。据我了解,在这里您需要以某种方式应用聚合

1 个答案:

答案 0 :(得分:3)

使用annotate()prefetch_related()

models.py

class CreditPayment(models.Model):
    credit = models.ForeignKey(Credit, related_name='creditpayments')
    ....

views.py

from django.db.models import Max, Min, Prefetch

prefetch = Prefetch('creditpayments', CreditPayment.objects.all())
sorted_credits = Credit.objects.all().prefetch_related(prefetch).annotate(min_rate=Min('creditpayments__rate')).annotate(max_period_to=Max('creditpayments__period_to')).order_by('min_rate', '-max_period_to')