gpt4 book ai didi

django - 我可以拥有一个未签名的 AutoField 吗?

转载 作者:行者123 更新时间:2023-12-03 21:31:12 25 4
gpt4 key购买 nike

我希望我的模型的主键是未签名的。因此我做这样的事情:

class MyModel(models.Model):
id = models.PositiveIntegerField(primary_key=True)

这让我得到一个 UNSIGNED我想要的结果 MySQL 表中的列。但是,我相信我不会自动分配给 id每次我创建一个新对象时,我会吗?这似乎需要使用 AutoField反而。问题是, AutoField已签署。有没有办法创建一个未签名的 AutoField ?

最佳答案

字段的实际类型在后端指定。在 MySQL 的情况下,后端是 django.db.backends.mysql .此摘录自 django/db/backends/mysql/creation.py显示此翻译:

class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'integer AUTO_INCREMENT',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
...

要改变这一点,你应该对这个 dict 进行猴子补丁:
from django.db.backends.mysql.creation import DatabaseCreation
DatabaseCreation.data_types['AutoField'] = 'integer UNSIGNED AUTO_INCREMENT'

或者你创建你自己的类,这样你就不会弄乱另一个 AutoFields :
from django.db.models.fields import AutoField
class UnsignedAutoField(AutoField):
def get_internal_type(self):
return 'UnsignedAutoField'

from django.db.backends.mysql.creation import DatabaseCreation
DatabaseCreation.data_types['UnsignedAutoField'] = 'integer UNSIGNED AUTO_INCREMENT'

然后创建您自己的 PK:
id = UnsignedAutoField()

当它从 AutoField 下降时,它将继承其所有行为。

关于django - 我可以拥有一个未签名的 AutoField 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com