models.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from django.db import connection, models
  2. class CurrentTranslation(models.ForeignObject):
  3. """
  4. Creates virtual relation to the translation with model cache enabled.
  5. """
  6. # Avoid validation
  7. requires_unique_target = False
  8. def __init__(self, to, on_delete, from_fields, to_fields, **kwargs):
  9. # Disable reverse relation
  10. kwargs['related_name'] = '+'
  11. # Set unique to enable model cache.
  12. kwargs['unique'] = True
  13. super().__init__(to, on_delete, from_fields, to_fields, **kwargs)
  14. class ArticleTranslation(models.Model):
  15. article = models.ForeignKey('indexes.Article', models.CASCADE)
  16. article_no_constraint = models.ForeignKey('indexes.Article', models.CASCADE, db_constraint=False, related_name='+')
  17. language = models.CharField(max_length=10, unique=True)
  18. content = models.TextField()
  19. class Article(models.Model):
  20. headline = models.CharField(max_length=100)
  21. pub_date = models.DateTimeField()
  22. # Add virtual relation to the ArticleTranslation model.
  23. translation = CurrentTranslation(ArticleTranslation, models.CASCADE, ['id'], ['article'])
  24. class Meta:
  25. index_together = [
  26. ["headline", "pub_date"],
  27. ]
  28. # Model for index_together being used only with single list
  29. class IndexTogetherSingleList(models.Model):
  30. headline = models.CharField(max_length=100)
  31. pub_date = models.DateTimeField()
  32. class Meta:
  33. index_together = ["headline", "pub_date"]
  34. # Indexing a TextField on Oracle or MySQL results in index creation error.
  35. if connection.vendor == 'postgresql':
  36. class IndexedArticle(models.Model):
  37. headline = models.CharField(max_length=100, db_index=True)
  38. body = models.TextField(db_index=True)
  39. slug = models.CharField(max_length=40, unique=True)
  40. class IndexedArticle2(models.Model):
  41. headline = models.CharField(max_length=100)
  42. body = models.TextField()