programing

장고: 색인 작성: 비고유, 다중 열

subpage 2023. 9. 6. 22:05
반응형

장고: 색인 작성: 비고유, 다중 열

다음 모델을 감안하여 필드(서열, 재고)를 색인화 하고자 합니다.

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,  

이 인덱스는 고유하지 않아야 합니다. mysql에서는 다음과 같아야 합니다.

create index ndx_1 on model_quotemodel(sequence,stock);

제가 아는 유일한 해결책은 테이블 생성 시에 django가 실행할 sql 파일을 만드는 것입니다.그래서 저는 다음과 같은 쿼리를 포함하는 "stockmodel.sql"을 만들었습니다. (위와 동일:).

create index ndx_1 on model_quotemodel(sequence,stock);

더 깨끗한 방법은 없을까요?

장고 1.5부터는 다음 옵션을 사용할 수 있습니다.

class QuoteModel(models.Model):
    # ... fields ...

    class Meta:
        index_together = [
            ("sequence", "stock"),
        ]

(참고: 2009년의 원답안은 여러 필드를 색인할 수 없다고 하였고, 이후 교체되었습니다.)

이 기능에 대한 티켓이 있습니다.http://code.djangoproject.com/ticket/5805 에서 만나보세요.

이 티켓에서 직접 패치를 적용할 수 있습니다.

갱신하다

이제 https://docs.djangoproject.com/en/1.5/ref/models/options/ #django.db.models.Options.index_together에 있습니다.

허용된 답변을 따라가기 위해 South를 사용하는 경우 다음과 같이 합성 키를 쉽게 추가할 수 있습니다.

manage.py schemamigration your_app_name_for_graphics --add-index ModelName.first_field_in_index

그런 다음 생성된 마이그레이션 파일을 편집하여 하나의 인덱스에 추가 필드를 추가할 수 있습니다(필요한 필드 이름 목록만 표시됨).

역방향 마이그레이션과 역방향 마이그레이션을 업데이트하는 것을 잊지 마십시오.

django 1.5에서 index_together입니다.

여기 https://docs.djangoproject.com/en/dev/ref/models/options/ #인덱스 함께 보기

unique_together 당신이 찾고 있는 것일 수도 있습니다.그냥 당신의 것에 넣어주세요.Meta모델 안에 클래스가 있습니다.

index_together 기능은 나중에 더 이상 사용되지 않을 수 있습니다.

index_together 대신 index 옵션을 사용해야 합니다.

인덱스 옵션의 예:

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'),
        ]

2022년 업데이트:

새로운 옵션은 다음보다 더 많은 기능을 제공합니다.index_together.index_together 는 장고 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'),
        ]

나는 단지 Django 1.11 이후에 Options.index라는 새로운 기능이 있다는 것을 추가하고 싶었을 뿐인데, 이것은 당신이 다음을 생성할 인덱스를 지정할 수 있게 해줄 것입니다.

Django Options

언급URL : https://stackoverflow.com/questions/1578195/django-create-index-non-unique-multiple-column

반응형