1
0
mirror of https://github.com/django/django.git synced 2024-12-25 18:46:22 +00:00
django/tests/modeltests/order_with_respect_to/models.py
Malcolm Tredinnick 9c52d56f6f Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.

Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658


git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00

79 lines
2.1 KiB
Python

"""
Tests for the order_with_respect_to Meta attribute.
"""
from django.db import models
class Question(models.Model):
text = models.CharField(max_length=200)
class Answer(models.Model):
text = models.CharField(max_length=200)
question = models.ForeignKey(Question)
class Meta:
order_with_respect_to = 'question'
def __unicode__(self):
return unicode(self.text)
__test__ = {'API_TESTS': """
>>> q1 = Question(text="Which Beatle starts with the letter 'R'?")
>>> q1.save()
>>> q2 = Question(text="What is your name?")
>>> q2.save()
>>> Answer(text="John", question=q1).save()
>>> Answer(text="Jonno",question=q2).save()
>>> Answer(text="Paul", question=q1).save()
>>> Answer(text="Paulo", question=q2).save()
>>> Answer(text="George", question=q1).save()
>>> Answer(text="Ringo", question=q1).save()
The answers will always be ordered in the order they were inserted.
>>> q1.answer_set.all()
[<Answer: John>, <Answer: Paul>, <Answer: George>, <Answer: Ringo>]
We can retrieve the answers related to a particular object, in the order
they were created, once we have a particular object.
>>> a1 = Answer.objects.filter(question=q1)[0]
>>> a1
<Answer: John>
>>> a2 = a1.get_next_in_order()
>>> a2
<Answer: Paul>
>>> a4 = list(Answer.objects.filter(question=q1))[-1]
>>> a4
<Answer: Ringo>
>>> a4.get_previous_in_order()
<Answer: George>
Determining (and setting) the ordering for a particular item is also possible.
>>> id_list = [o.pk for o in q1.answer_set.all()]
>>> a2.question.get_answer_order() == id_list
True
>>> a5 = Answer(text="Number five", question=q1)
>>> a5.save()
It doesn't matter which answer we use to check the order, it will always be the same.
>>> a2.question.get_answer_order() == a5.question.get_answer_order()
True
The ordering can be altered:
>>> id_list = [o.pk for o in q1.answer_set.all()]
>>> x = id_list.pop()
>>> id_list.insert(-1, x)
>>> a5.question.get_answer_order == id_list
False
>>> a5.question.set_answer_order(id_list)
>>> q1.answer_set.all()
[<Answer: John>, <Answer: Paul>, <Answer: George>, <Answer: Number five>, <Answer: Ringo>]
"""
}