Skip to main content
 首页 » 编程设计

python之Django 1.6 中的部分索引

2025年05月04日37zhengyun_ustc

我有以下模型,

class Payment(AbstractBaseModel): 
 
    sales_order = models.ForeignKey( 
        'salesorders.SalesOrder', 
        verbose_name=_('Sales Order'), 
        unique=True) 
    invoice = models.ForeignKey( 
        'accounting.Invoice', 
        help_text=_('invoice to which the payment belongs to'), 
        verbose_name=_('invoice'), 
        null=True,blank=True 
    ) 

两者都是唯一的,并且一起索引,

所以我通过添加 class Meta 选项来重写我的上述模型

class Payment(AbstractBaseModel): 
 
    sales_order = models.ForeignKey( 
        'salesorders.SalesOrder', 
         verbose_name=_('Sales Order'), 
         unique=True) 
    invoice = models.ForeignKey( 
        'accounting.Invoice', 
        help_text=_('invoice to which the payment belongs to'), 
        verbose_name=_('invoice'), 
        null=True,blank=True 
    ) 
 
    class Meta: 
        app_label = 'payments' 
        unique_together = ('sales_order','invoice') 
        index_together = [['sales_order','invoice']] 

这不合逻辑,因为这些字段实际上是彼此的部分索引,所以我的django版本是1.6,遇到这种情况我该怎么办?

请您参考如下方法:

您确实需要升级到受支持的 django 版本 - 因为有 quite a few security updates你失踪了。

在 1.7 中,通过迁移支持部分索引 - 这本身就是从 South 项目吸收的功能。

您可以(并且应该)使用 South - 创建一个空迁移,并使用 custom SQL创建您的部分索引。

这也是 django 的内置迁移提供的解决方案,但它们对命令有不同的包装;使用 RunSQL。