我正在写一个非常简单的搜索视图:
@Override
public void computeScroll() {
super.computeScroll();
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
结果应按选择总票数排序:
class SearchView(generic.ListView):
template_name = 'polls/search.html'
context_object_name = 'results'
def get_queryset(self):
"""
Extract query from parameters and return search results.
"""
query = self.request.GET.get('query')
if query:
query = query.strip()
return Question.objects.filter(question_text__icontains=query)
else:
return Question.objects.none()
<!DOCTYPE html>
{% if results %}
<ul>
{% for result in results %}
<li><a href="{% url 'polls:vote' result.id %}">{{ result }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No matches found.</p>
{% endif %}
<p><a href="{% url 'polls:index' %}">Back to overview?</a></p>
答案 0 :(得分:1)
如果您附加问题 Django模型,也许它很有用,因为我不了解您的错误。
关于分页,这里有一些我在我的应用程序中使用的有用的Django类:
https://docs.djangoproject.com/en/1.10/topics/pagination/
使用起来非常简单。
答案 1 :(得分:0)
谢谢!分页正是我所寻找的。 p>
我想在反向外键关系船上进行查询:
class Question(models.Model):
question_text = models.CharField('text', max_length=200)
pub_date = models.DateTimeField('publication date', default=timezone.now)
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField('text', max_length=200)
votes = models.IntegerField('votes', default=0)
def __str__(self):
return self.choice_text
解决方案是使用注释:
results.annotate(total_votes=Sum('choice__votes')).order_by('-total_votes')