【问题标题】:django simple history field indexingdjango简单的历史字段索引
【发布时间】:2020-10-14 18:18:48
【问题描述】:

如何告诉 DSH 索引特定字段?我对历史模型进行的一些查询花费了太多时间

我有基本的抽象模型,我的所有模型都继承自该模型。这个基本模型中也定义了历史字段:

class BaseModel(models.Model):
    class PublishingStatus(models.TextChoices):
        DRAFT = 'draft', _('Draft')
        ACCEPTED = 'accepted', _('Accepted'),
        REJECTED = 'rejected', _('Rejected'),
        MODIFIED = 'modified', _('Modified')

    publishing_status = models.CharField(
        max_length=9,
        choices=PublishingStatus.choices,
        default=PublishingStatus.DRAFT,
        help_text=_("Publishing status represents the state of the object. By default it is 'draft'")
    )

    history = HistoricalRecords(inherit=True)

我还在这个基本模型中添加了索引

class Meta:
    abstract = True
    indexes = [models.Index(fields=[
        'publishing_status',
    ])]

如果 Django Simple History 可以检查哪些字段被索引并在历史模型中创建相同的索引,那就太好了

也许有一种方法可以明确地告诉 django 简单历史必须另外索引哪个字段?

【问题讨论】:

    标签: django django-simple-history


    【解决方案1】:

    我希望有更好的解决方案,但我最终创建了一个自定义迁移文件。首先,我为应用创建了一个空白迁移文件:

    python manage.py makemigrations dosh --empty
    

    然后我修改了这个新创建的空迁移文件,并为每个历史模型添加了AddIndex

    # Generated by Django 3.1.1 on 2020-10-15 06:49
    
    from django.db import migrations, models
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('dosh', '0002_auto_20201008_2155'),
        ]
    
        operations = [
            # ...
            migrations.AddIndex(
                model_name='historicaltense',
                index=models.Index(fields=['publishing_status'], name='htense_publish_status_idx')
            ),
            migrations.AddIndex(
                model_name='historicalsynonym',
                index=models.Index(fields=['publishing_status'], name='hsynonym_publish_status_idx')
            ),
            # ...
        ]
    

    最后,我已经迁移了这些更改

    python manage.py migrate
    Operations to perform:
      Apply all migrations: admin, auth, authtoken, comment, contenttypes, dosh, pinax_badges, sessions, social, users, vote
    Running migrations:
      Applying dosh.0003_auto_20201015_0849... OK
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多