models.py 1012 B

1234567891011121314151617181920212223242526272829303132333435
  1. """
  2. 6. Specifying ordering
  3. Specify default ordering for a model using the ``ordering`` attribute, which
  4. should be a list or tuple of field names. This tells Django how to order
  5. ``QuerySet`` results.
  6. If a field name in ``ordering`` starts with a hyphen, that field will be
  7. ordered in descending order. Otherwise, it'll be ordered in ascending order.
  8. The special-case field name ``"?"`` specifies random order.
  9. The ordering attribute is not required. If you leave it off, ordering will be
  10. undefined -- not random, just undefined.
  11. """
  12. from django.db import models
  13. from django.utils.encoding import python_2_unicode_compatible
  14. class Author(models.Model):
  15. class Meta:
  16. ordering = ('-pk',)
  17. @python_2_unicode_compatible
  18. class Article(models.Model):
  19. author = models.ForeignKey(Author, null=True)
  20. headline = models.CharField(max_length=100)
  21. pub_date = models.DateTimeField()
  22. class Meta:
  23. ordering = ('-pub_date', 'headline')
  24. def __str__(self):
  25. return self.headline