我有一个模型,我试图按最高评级平均排序,但它似乎没有做正确的排序。
在我的views.py中,我有:
restaurants = Restaurant.objects.all().order_by('-rating__rating_average')
我的模型定义将字段定义为:
rating_average = models.FloatField()
但是,此查询似乎返回随机排序。我忽略了什么吗?如何使用FloatField完成此查询?
这是我的models.py文件及相关模型:
class Rating(models.Model):
restaurant = models.OneToOneField('restaurant.Restaurant', primary_key=True)
one_star_total= models.IntegerField()
two_star_total= models.IntegerField()
three_star_total= models.IntegerField()
four_star_total= models.IntegerField()
five_star_total= models.IntegerField()
number_of_ratings = models.IntegerField()
total_rating_value = models.IntegerField()
rating_average = models.FloatField()
def __str__(self): # __unicode__ on Python 2
return self.restaurant.restaurant_name
class Restaurant(models.Model):
user = models.OneToOneField(User)
restaurant_name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
address2= models.CharField(max_length=100, default= "null", blank=True,null=True)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.IntegerField()
phone = models.CharField(max_length=15)
website_link= models.CharField(max_length=200, blank=True, null=True)
category= models.CharField(max_length=100)
pub_date = models.DateTimeField(default=timezone.now,blank=True)
def __str__(self): # __unicode__ on Python 2
return self.restaurant_name
答案 0 :(得分:0)
也许是因为null值,但是正因为如此,它对我没有用。
我使用Django的F函数解决了此问题,以计算空值,如下所示:
from django.db.models import F
restaurants = Restaurants.objects.order_by(F('rating_average').desc(nulls_last=True))
Django的文档-link。