我陷入了这个问题:
我有两个模型:
位置和价格。
每个位置都有它的费率,可能有多个费率。
我想按其费率升序排列位置。
显然,order_by
不要distinct()
一起工作:
locations = Location.objects.filter(**s_kwargs).order_by('locations_rate__rate').distinct('id')
然后我阅读了文档并来到了annotate()
. 但我不确定是否必须在注释之间使用函数。
如果我这样做:
locations = Location.objects.filter(**s_kwargs).annotate(rate=Count('locations_rate__rate')).order_by('rate')
但这会按总和计算费率和订单。我想获取按这些费率的值排序的费率位置。
我的模型定义是:
class Location(models.Model):
name = models.TextField()
adres = models.TextField()
class Rate(models.Model):
location = models.ForeignKey(Location,related_name='locations_rate')
rate = models.IntegerField(max_length=2)
price_rate = models.IntegerField(max_length=2) #<--- added now
datum = models.DateTimeField(auto_now_add=True,blank=True) #<--- added now