jba*_*tos 28 mysql django indexing
鉴于以下模型,我想索引字段(序列,库存)
class QuoteModel(models.Model):
quotedate = models.DateField()
high = models.FloatField() #(9,2) DEFAULT NULL,
low = models.FloatField() #(9,2) DEFAULT NULL,
close = models.FloatField() #(9,2) DEFAULT NULL,
closeadj = models.FloatField() #(9,2) DEFAULT NULL,
volume = models.IntegerField() #(9,2) DEFAULT NULL,
stock = models.IntegerField(db_index=True) #(9,2) DEFAULT NULL,
open = models.FloatField() #(9,2) DEFAULT NULL,
sequence = models.IntegerField() #(9,2) DEFAULT NULL,
Run Code Online (Sandbox Code Playgroud)
这个索引应该是非唯一的 - 在mysql中它应该是这样的:
create index ndx_1 on model_quotemodel(sequence,stock);
Run Code Online (Sandbox Code Playgroud)
我所知道的唯一的Django解决方法是创建一个"sql"文件,该文件将在创建表时由django执行.所以,我创建了一个包含以下查询的"stockmodel.sql"(与上面相同:)
create index ndx_1 on model_quotemodel(sequence,stock);
Run Code Online (Sandbox Code Playgroud)
这样做有"更干净"的方法吗?
Iva*_*yan 21
这个功能有一张票.看看http://code.djangoproject.com/ticket/5805
您可以自己应用此票证中的补丁.
UPDATE
它现在在Django:https://docs.djangoproject.com/en/1.5/ref/models/options/#django.db.models.Options.index_together
exc*_*eve 18
从Django 1.5开始,您可以使用以下Meta.index_together选项:
class QuoteModel(models.Model):
# ... fields ...
class Meta:
index_together = [
("sequence", "stock"),
]
Run Code Online (Sandbox Code Playgroud)
(注意:2009年的原始答案说不可能索引多个字段;它已被替换)
cas*_*ere 14
在django 1.5中它是index_together
在这里看到https://docs.djangoproject.com/en/dev/ref/models/options/#index-together
cra*_*esh 10
unique_together可能就是你要找的东西.只需将它Meta放在模型中的类中即可.
The index_together feature could be deprecated in the futur.
You should use indexes option instead of index_together.
Example of indexes option :
from django.db import models
class Customer(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Meta:
indexes = [
models.Index(fields=['last_name', 'first_name']),
models.Index(fields=['first_name'], name='first_name_idx'),
]
Run Code Online (Sandbox Code Playgroud)
2022 年更新:
较新的indexes选项提供了比index_together. index_together 在 Django 4.1 中已弃用。
用法:
from django.db import models
class Customer(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Meta:
indexes = [
models.Index(fields=['last_name', 'first_name']),
models.Index(fields=['first_name'], name='first_name_idx'),
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24709 次 |
| 最近记录: |