0

I have a model with replies and in template the replies with highest upvote should come first.

In my local machine its coming correctly however on server replies are filtered based on FK of upvote field.

Model:

class solution(models.Model):
    doubt=models.ForeignKey(doubts,related_name='answers')
    reply=models.TextField()
    snapshot = models.FileField(upload_to='support',null=True,blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    user=models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True)
    upvote = models.ManyToManyField(User,related_name='upvoteuser')

    @property
    def total_upvotes(self):
        return self.upvote.count()

    def __str__(self):
        return str(self.doubt)

view

def ticketdetails(request,slug,pk):
    ticketis=doubts.objects.get(pk=pk)
    replies = ticketis.answers.all().order_by('-upvote')


    if request.method== 'POST':
        form=replyform(request.POST)
        if form.is_valid():
            new_form=form.save(commit=False)
            new_form.user=request.user
            new_form.doubt=ticketis
            new_form.save()
            form=replyform()
            return HttpResponseRedirect(reverse('ticketdetail',kwargs={'slug':ticketis.slug,'pk':ticketis.id}),messages.add_message(request, messages.SUCCESS,'Response submitted succesfully.'))
    else:
        form=replyform()    
    return render(request,'ticketview.html',{'ticketis':ticketis,'replies':replies,'form':form})
2
  • What part of the upvote model are you trying to order on? does that have any ordering specified? Commented Nov 30, 2016 at 8:06
  • Upvote field with most upvotes count should be first. Commented Nov 30, 2016 at 8:07

1 Answer 1

2

Upvote field with most upvotes count should be first.

This isn't what your ordering is doing, at all

From the docs:

If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model, or order by the related model’s primary key if there is no Meta.ordering specified.

If you're trying to order by the count of something then you'll need to annotate it first and then order based on that

Your view is talking about a different model to the one you've shown but the solution will still look similar to below

 Solution.objects.annotate(upvote_count=Count('upvote')).order_by('upvote_count')
Sign up to request clarification or add additional context in comments.

2 Comments

@PulkitSharma - Pure luck.
Local machine works with your code either because it's pure luck or because you are using a lesser RDBMS. Postgresql is much closer to standard compliance and sqlite

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.