2013-04-20 85 views
0

我尝试着获取对象排序。这是我的代码:Django Queryset按order_by与relatedManager排序

ratings = Rate.objects.order_by(sortid) 
locations = Location.objects.filter(locations_rate__in=ratings).order_by('locations_rate').distinct('id') 

这是我的模型:

class Rate(models.Model): 
    von_location= models.ForeignKey(Location,related_name="locations_rate") 
    price_leistung = models.IntegerField(max_length=5,default=00) 
    bewertung = models.IntegerField(max_length=3,default=00) 

我怎么能得到的顺序是相等的ratings所有位置?

我以上没有工作。
编辑

def sort(request): 
    sortid = request.GET.get('sortid') 
    ratings = Rate.objects.all() 
    locations = Location.objects.filter(locations_rate__in=ratings).order_by('locations_rate__%s' % sortid).distinct('id') 
    if request.is_ajax(): 
    template = 'resultpart.html' 
    return render_to_response(template,{'locs':locations},context_instance=RequestContext(request)) 
+0

什么是'sortid'? – 2013-04-20 07:48:13

+0

@PavelAnossov,它可以是''price_leistung''或''bewertung'' – doniyor 2013-04-20 07:49:01

回答

2

您必须指定一个字段用于排序的Rate对象,例如:

ratings = Rate.objects.all() 
locations = Location.objects.filter(
    locations_rate__in=ratings 
).order_by('locations_rate__%s' % sortid).distinct('id') 

你不需要预先排序ratings

documentation提供了相关字段上使用order_by的示例。

+0

谢谢,但它是在说。 ''view home.views.sort没有返回一个HttpResponse对象.''。这个查询中有些错误。 – doniyor 2013-04-20 08:02:51

+0

我认为这是另一个问题:)您的观点需要返回一些数据,如[文档](https://docs.djangoproject.com/en/dev/topics/http/views/)中所述。你应该发布你的视图代码,如果你需要更多的帮助在这一点 – 2013-04-20 08:06:19

+0

我将这作为ajax响应返回,我正在呈现一些内部呈现数据的HTML部分。所以HttpResponse不应该在那里。请在我的更新中看到我的视图 – doniyor 2013-04-20 08:14:05