2

I am tryint to get objects sorted. this is my code:

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

this is my model:

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)

how can I get all Locations in that order which is equal to that of ratings?

what I have above isnot working.
EDIT:

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))
doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

2

You must specify a field to use for sorting the Rate objects, for example:

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

You do not need to sort ratings beforehand.

The documentation provides example of use of order_by on related fields.

Nicolas Cortot
  • 6,591
  • 34
  • 44
  • thanks, but it is saying. ``The view home.views.sort didn't return an HttpResponse object.``. something is wrong in this query. – doniyor Apr 20 '13 at 08:02
  • I believe that's another question :) Your view need to return some data, as explained in the [documentation](https://docs.djangoproject.com/en/dev/topics/http/views/). You should post your view code if you need more help on this point – Nicolas Cortot Apr 20 '13 at 08:06
  • I am returning this as ajax response, i am rendering some html part with data rendered inside. so HttpResponse shouldnot be there. please see my view in my update – doniyor Apr 20 '13 at 08:14
  • Nothing looks wrong to me, `render_to_response` will return an `HttpResponse `. I guess the `request.is_ajax()` evaluates to `False` in your view then, are you sure you're accessing it through an AJAX call? Also, even if your view only supports AJAX requests, you should handle all types of response, for example return `HttpResponseBadRequest` or ` for non-AJAX requests, this will help debugging. – Nicolas Cortot Apr 20 '13 at 08:40
  • I am using Jquery load, i think, this is the reason. – doniyor Apr 20 '13 at 10:41