已经有很多关于此的文档,但无法让其中任何一个为我工作。就像标题暗示的那样,试图获取一组使用 Django Voting 的对象,根据他们的投票数(从高到低)进行排序。已经尝试过这个和其他一些,但没有任何成果。
使用 Django 投票,这里是 URL Conf & HTML
#urls.py
url(r'^$', 'questions'),
url(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)/vote/$',
vote_on_object, dict(model = Question, template_object_name = 'question',
template_name = 'qanda/confirm_vote.html', post_vote_redirect = '/home/', allow_xmlhttprequest=True)),
URLconf 中的问题会导致呈现 questions.html 的问题视图
#questions.html
{% load voting_tags %}
{% votes_by_user user on the_question as vote_dict %}
{% scores_for_objects the_question as score_dict %}
<div class="question">
{% if the_question %}
<ul>
{% for question in the_question %}
{% dict_entry_for_item question from vote_dict as vote %}
{% dict_entry_for_item question from score_dict as score %}
<div class="votearrowdiv">
<div class="upvotearrow"></div></a>
<form class="linkvote" id="linkup{{ question.id }}" action="/home/{{ question.id }}/{% if vote and vote.is_upvote %}clear{% else %}up{% endif %}/vote/" method="POST">
{% csrf_token %}
<input type="image" id="linkuparrow{{ question.id }}" src="{{ media_url }}img/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.png">
</form>
<div class="downvotearrow"></div></a>
<form class="linkvote" id="linkdown{{ question.id }}" action="/home/{{ question.id }}/{% if vote and vote.is_downvote %}clear{% else %}down{% endif %}/vote/" method="POST">
{% csrf_token %}
<input type="image" id="linkdownarrow{{ question.id }}" src="{{ media_url }}img/adown{% if vote and vote.is_downvote %}mod{% else %}grey{% endif %}.png">
</form>
</div>
<li>
<div class="votecounter"><div class="numbercount">
<span class="score" id="linkscore{{ question_id }}"
title="after {{ score.num_votes|default:0 }} vote{{ score.num_votes|default:0|pluralize }}">
{{ score.score|default:0 }}
</span>
</div></div>
<a href="/home/{{ movie.id }}/{{ question.id }}/">{{ question.question_text }}</a>
{% endfor %}
{% endif %}
这是我目前的看法:
#views.py
def questions(request, movie_id):
p = Movie.objects.get(pk=movie_id)
k = Question.objects.filter(movie=p).order_by('q_pub_date')
l = k.reverse()
return render_to_response('qanda/questions.html', {'movie':p, 'the_question':l}, context_instance = RequestContext(request))
我知道我不能使用“分数”进行排序,因为它不在模型中。我需要更改哪些视图才能正确排序?
编辑:
罗伯特,这里是 models.py。尝试了您的解决方案和许多变体,但我没有该模型的投票属性。看一看:
#models.py
class Question(models.Model):
movie = models.ForeignKey(Movie, blank=True, null=True)
question_text = models.CharField(verbose_name = "Question", max_length = 250)
question_detail = models.CharField(verbose_name = "Details (Optional)", max_length = 5000, blank = True, null = True)
q_pub_date = models.DateTimeField(auto_now_add = True)
q_author = models.ForeignKey(User)
有什么见解吗?