【问题标题】:Django: add index to meta fieldDjango:向元字段添加索引
【发布时间】:2015-10-16 15:53:09
【问题描述】:

我有以下型号:

from model_utils.models import TimeStampedModel
class MyModel(TimeStampedModel):
    ....
    name = models.CharField(max_length=100)
    ....

此模型基于 Django Utils (https://django-model-utils.readthedocs.org/en/latest/models.html#timestampedmodel),它将 createdmodified 字段添加到我的模型中。

我需要知道的是如何将db_index 添加到我的模型的修改字段中。但我无法修改 TimeStampedModel 文件,因为它是外部依赖项的一部分。

您知道此类问题的任何简单解决方案吗?

谢谢。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    是的,您可以使用模型 Meta。

    如果您不需要从 TimeStampedModel 继承元数据,只需使用这个:

    class Meta:
       ...
    

    否则你需要像这样明确告诉 django 首先查看父级的元数据:

    class Meta(TimeStampedModel.Meta):
    

    这可能是一个骇人听闻的解决方案,但也许您可以尝试使用 index_together 让 django 为您的模型创建索引:

    像这样:

    class Meta(TimeStampedModel.Meta):
        index_together = [
            ["modified",],
        ]
    

    试一试,告诉我它是否有效

    编辑:

    另一个解决方案来自:How to override the default value of a Model Field from an Abstract Base Class:

    尝试将此添加到您的 MyModel 类中

    MyModel._meta.get_field('modified').db_index = True
    

    【讨论】:

    • 我使用了最后一个解决方案,效果很好。比 index_together 少 hacky。
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2023-03-31
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多