簡體   English   中英

大於 Django 中的索引

[英]Greater than Index in Django

在 Django-3.2 class 索引獲取位置參數表達式,它允許在表達式上創建功能索引

是否可以在表達式更大的 Integer 字段上創建索引? 例如

我的 model:

class Product(models.Model):
    description = models.CharField(max_length=50)
    delivery_date = models.DateTimeField(null=True)
    quantity = models.IntegerField(validators=[MinValueValidator(0)])

通常我有一個過濾器(數量> 0)。 如何在上面創建表達式索引?

您可以使用ExpressionWrapper創建功能索引:

from django.db.models import BooleanField, ExpressionWrapper, Index, Q

class Product(models.Model):
    # …

    class Meta:
        indexes = [
            Index(
                ExpressionWrapper(
                    Q(quantity__gt=0),
                    output_field=BooleanField()
                ),
            name=''
          )
        ]

這將在 SQL 中翻譯為:

CREATE INDEX ``
          ON `app_name_product` ((`quantity` > 0));

然而,通常db_index=True [Django-doc]足以加速過濾器,因為這些通常由一些樹狀結構實現,因此將確定要在O(log n)中檢索的對象。

因此,我們可以將其設置為:

class Product(models.Model):
    # …
    quantity = models.IntegerField(
        db_index=True,
        validators=[MinValueValidator(0)]
    )

這將合理地快速工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM