Auto-created primary key used when not defining a primary key

When you define a model in Django without specifying a primary key, Django will automatically create a primary key for you. The primary key is set to be an integer. If you want to override the field type, you can do so on a per model basis.

Starting in Django 3.2, you can now customise the type of the automatically created primary key in your settings.

Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer. However, earlier versions set the type of implicit primary keys to be integers.

This means that when you upgrade to 3.2, you will start to see warnings about the fact that you do not have an explicitly defined primary key type. Satisfying Django's requirements for an explicitly set primary key type is easy enough, but you also need to choose whether or not you want to upgrade your primary key field types from integer to 64 bit integer.

There are a few ways to fix this. Broadly speaking they fall into two categories

Configure DEFAULT_AUTO_FIELD in settings

Open your project's settings.py and add a new line at the bottom of the file

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

Setting on a per app basis

If you prefer to set your field type on a per app basis rather than for the whole project, you can specify this in apps.py.

from django.apps import AppConfig

class MyappConfig(AppConfig):
    default_auto_field = 'django.db.models.AutoField'
    name = 'Myapp'

Set AutoField or BigAutoField on a per model basis

If you prefer even more fine grained control, you can set a per model id field.

class Model1(models.Model):
    id = models.BigAutoField(primary_key=True)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值