models.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. 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. class Author(models.Model):
  14. name = models.CharField(max_length=63, null=True, blank=True)
  15. class Meta:
  16. ordering = ('-pk',)
  17. class Article(models.Model):
  18. author = models.ForeignKey(Author, models.SET_NULL, null=True)
  19. second_author = models.ForeignKey(Author, models.SET_NULL, null=True, related_name='+')
  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
  26. class OrderedByAuthorArticle(Article):
  27. class Meta:
  28. proxy = True
  29. ordering = ('author', 'second_author')
  30. class OrderedByFArticle(Article):
  31. class Meta:
  32. proxy = True
  33. ordering = (models.F('author').asc(nulls_first=True), 'id')
  34. class Reference(models.Model):
  35. article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE)
  36. class Meta:
  37. ordering = ('article',)