db.models.Options.order_with_respect_to

Options.order_with_respect_to

Makes this object orderable with respect to the given field, usually a ForeignKey. This can be used to make related objects orderable with respect to a parent object. For example, if an Answer relates to a Question object, and a question has more than one answer, and the order of answers matters, you’d do this:

from django.db import models

class Question(models.Model):
    text = models.TextField()
    # ...

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    # ...

    class Meta:
        order_with_respect_to = 'question'

When order_with_respect_to is set, two additional methods are provided to retrieve and to set the order of the related objects: get_RELATED_order() and set_RELATED_order(), where RELATED is the lowercased model name. For example, assuming that a Question object has multiple related Answer objects, the list returned contains the primary keys of the related Answer objects:

>>> question = Question.objects.get(id=1)
>>> question.get_answer_order()
[1, 2, 3]

The order of a Question object’s related Answer objects can be set by passing in a list of Answer primary keys:

>>> question.set_answer_order([3, 1, 2])

The related objects also get two methods, get_next_in_order() and get_previous_in_order(), which can be used to access those objects in their proper order. Assuming the Answer objects are ordered by id:

>>> answer = Answer.objects.get(id=2)
>>> answer.get_next_in_order()
<Answer: 3>
>>> answer.get_previous_in_order()
<Answer: 1>

order_with_respect_to implicitly sets the ordering option

Internally, order_with_respect_to adds an additional field/database column named _order and sets the model’s ordering option to this field. Consequently, order_with_respect_to and ordering cannot be used together, and the ordering added by order_with_respect_to will apply whenever you obtain a list of objects of this model.

Changing order_with_respect_to

Because order_with_respect_to adds a new database column, be sure to make and apply the appropriate migrations if you add or change order_with_respect_to after your initial migrate.

doc_Django
2016-10-09 18:36:00
Comments
Leave a Comment

Please login to continue.