| 1 |
from django.db import models |
| 2 |
|
| 3 |
|
| 4 |
class CurrentTranslation(models.ForeignObject): |
| 5 |
""" |
| 6 |
Creates virtual relation to the translation with model cache enabled. |
| 7 |
""" |
| 8 |
|
| 9 |
# Avoid validation |
| 10 |
requires_unique_target = False |
| 11 |
|
| 12 |
def __init__(self, to, on_delete, from_fields, to_fields, **kwargs): |
| 13 |
# Disable reverse relation |
| 14 |
kwargs["related_name"] = "+" |
| 15 |
# Set unique to enable model cache. |
| 16 |
kwargs["unique"] = True |
| 17 |
super().__init__(to, on_delete, from_fields, to_fields, **kwargs) |
| 18 |
|
| 19 |
|
| 20 |
class ArticleTranslation(models.Model): |
| 21 |
article = models.ForeignKey("indexes.Article", models.CASCADE) |
| 22 |
article_no_constraint = models.ForeignKey( |
| 23 |
"indexes.Article", models.CASCADE, db_constraint=False, related_name="+" |
| 24 |
) |
| 25 |
language = models.CharField(max_length=10, unique=True) |
| 26 |
content = models.TextField() |
| 27 |
|
| 28 |
|
| 29 |
class Article(models.Model): |
| 30 |
headline = models.CharField(max_length=100) |
| 31 |
pub_date = models.DateTimeField() |
| 32 |
published = models.BooleanField(default=False) |
| 33 |
|
| 34 |
# Add virtual relation to the ArticleTranslation model. |
| 35 |
translation = CurrentTranslation( |
| 36 |
ArticleTranslation, models.CASCADE, ["id"], ["article"] |
| 37 |
) |
| 38 |
|
| 39 |
class Meta: |
| 40 |
indexes = [models.Index(fields=["headline", "pub_date"])] |
| 41 |
|
| 42 |
|
| 43 |
class IndexedArticle(models.Model): |
| 44 |
headline = models.CharField(max_length=100, db_index=True) |
| 45 |
body = models.TextField(db_index=True) |
| 46 |
slug = models.CharField(max_length=40, unique=True) |
| 47 |
|
| 48 |
class Meta: |
| 49 |
required_db_features = {"supports_index_on_text_field"} |
| 50 |
|
| 51 |
|
| 52 |
class IndexedArticle2(models.Model): |
| 53 |
headline = models.CharField(max_length=100) |
| 54 |
body = models.TextField() |