Django


1555 浏览 6 years, 1 month

4.6 前后实例

版权声明: 转载请注明出处 http://www.codingsoho.com/

Django DateTimeField add the get_previous_by_ only. If you want by title you must create your own methods. It doesn't show anything because Django template system fails silently.

Django Model class has a _get_next_or_previous_by_FIELD, and you can create the following:

class MyModel(models.Model):
    [fields]
    def get_next_by_title(self):
        field = self.__class__._meta.get_field('title')
        try:
            return self._get_next_or_previous_by_FIELD(field , is_next=True)
        except MyModel.DoesNotExist:
            return None

    def get_previous_by_title(self):
        field = self.__class__._meta.get_field('title')
        try:
            return self._get_next_or_previous_by_FIELD(field , is_next=False)
        except MyModel.DoesNotExist:
            return None

Template:

  <a class="col-md-6" href="{{ object.get_previous_by_title.get_absolute_url }}" title="{% trans "revious" %}">&laquo; {{ object.get_previous_by_title.title }}</a>
  <a class="col-md-6" href="{{ object.get_next_by_title.get_absolute_url }}" title="{% trans "next" %}">&raquo; {{ object.get_next_by_title.title }}</a>

实例:英语联想记单词