8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BigIntegerFieldをauto incrementにする

Last updated at Posted at 2015-09-13

忘れてしまいそうなので、自分用にメモ。
DjangoではAutoFieldというのがありますが、それで作成されるdatabaseのclumnはintになってしまいます。

bigint でauto incrementさせたい。
stackoverflowに親切な人がいた。

from django.db.models import fields
from south.modelsinspector import add_introspection_rules

class BigAutoField(fields.AutoField):
    def db_type(self, connection):
        if 'mysql' in connection.__class__.__module__:
            return 'bigint AUTO_INCREMENT'
        return super(BigAutoField, self).db_type(connection)

add_introspection_rules([], ["^MYAPP\.fields\.BigAutoField"])

southを使用しない人は

from django.db.models import fields

class BigAutoField(fields.AutoField):
    def db_type(self, connection):
        if 'mysql' in connection.__class__.__module__:
            return 'bigint AUTO_INCREMENT'
        return super(BigAutoField, self).db_type(connection)


これでいいみたいです。

#実験
まずテストのモデル用意
AutoIncrementを使用するときの注意としては、他のfieldで使用されてしまっていた場合

A model can't have more than one AutoField.

と出て怒られます。

from django.db import models
class test(models.Model):
	id = BigAutoField(primary_key=True)
python manage.py syncdb

#結果
スクリーンショット 2015-09-13 16.58.14.png

auto_incrementになってました!

補足や間違いあれば、ご指摘お願いします。

参考:
http://stackoverflow.com/questions/2672975/django-biginteger-auto-increment-field-as-primary-key

8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?