双下划线方法,用于根据另一个不起作用的模型中的字段对视图返回的列表进行排序

时间:2017-11-30 02:47:57

标签: python django

我正在尝试根据另一个模型中的字段对视图返回的列表进行排序。我读了documentation over here,如果在模型的元数据中指定了排序,它就说我可以通过使用模型的名称来做到这一点。

查看

/*
Basic Regex explanation:
/                   Regex start
(\w+)               First group, words     \w means ASCII letter with \w     + means 1 or more letters
|                   or
(,|!)               Second group, punctuation
|                   or
(\s)                Third group, white spaces
/                   Regex end
g                   "global", enables looping over the string to capture one element at a time

Regex result:
result[0] : default group : any match
result[1] : group1 : words
result[2] : group2 : punctuation , !
result[3] : group3 : whitespace
*/
var basicRegex = /(\w+)|(,|!)|(\s)/g;

/*
Advanced Regex explanation:
[a-zA-Z\u0080-\u00FF] instead of \w     Supports some Unicode letters instead of ASCII letters only. Find Unicode ranges here https://apps.timwhitlock.info/js/regex

(\.\.\.|\.|,|!|\?)                      Identify ellipsis (...) and points as separate entities

You can improve it by adding ranges for special punctuation and so on
*/
var advancedRegex = /([a-zA-Z\u0080-\u00FF]+)|(\.\.\.|\.|,|!|\?)|(\s)/g;

var basicString = "Hello, this is a random message!";
var advancedString = "Et en français ? Avec des caractères spéciaux ... With one point at the end.";

console.log("------------------");
var result = null;
do {
    result = basicRegex.exec(basicString)
    console.log(result);
} while(result != null)

console.log("------------------");
var result = null;
do {
    result = advancedRegex.exec(advancedString)
    console.log(result);
} while(result != null)

/*
Output:
Array [ "Hello",        "Hello",        undefined,  undefined ]
Array [ ",",            undefined,      ",",        undefined ]
Array [ " ",            undefined,      undefined,  " "       ]
Array [ "this",         "this",         undefined,  undefined ]
Array [ " ",            undefined,      undefined,  " "       ]
Array [ "is",           "is",           undefined,  undefined ]
Array [ " ",            undefined,      undefined,  " "       ]
Array [ "a",            "a",            undefined,  undefined ]
Array [ " ",            undefined,      undefined,  " "       ]
Array [ "random",       "random",       undefined,  undefined ]
Array [ " ",            undefined,      undefined,  " "       ]
Array [ "message",      "message",      undefined,  undefined ]
Array [ "!",            undefined,      "!",        undefined ]
null
*/

模型

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
    ordering = ['choice']

模板(轮询/ results.html)

  class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
      return self.choice_text

     class Meta:
         ordering = ['-votes']

我做到了,它有效,但我有不同的观点,需要以不同的方式订购相同的模型,例如一个用它的名字,另一个用投票。我怎样才能实现这样的目标呢?

例如我正在寻找像

这样的东西

查看1

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

查看2

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
    ordering = ['-choice__votes']

1 个答案:

答案 0 :(得分:1)

您可以在视图类而不是模型上指定queryset属性,并将顺序添加到该属性。

class DetailView(generic.DetailView):
    queryset = Question.objects.all().order_by('-choice__choice_text')

修改

您需要专门订购选项,而不是问题。通常,您在查找选项时通过添加order_by调用来执行此操作,但由于您在模板中执行此操作,因此无法在其中传递排序值。相反,您可以在Question类本身上定义两个方法,它们以相关顺序返回选项:

class Question(models.Model):
    ...
    def choices_by_votes(self):
        return self.choice_set.order_by('-votes')

    def choices_by_text(self):
        return self.choice_set.order_by('choice_text')

并在模板中使用它们:

{% for choice in question.choices_by_votes %}