Reputation: 262
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})
Upvotes: 0
Views: 184
Reputation: 43330
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')
Upvotes: 2