Django:非主键自动递增字段

时间:2020-04-06 04:35:26

标签: django autofield

有没有可能创建像non primary-key auto incremented field这样的AutoField/BigAutoField而不容易失败的方法(重复的ID,...)?

2 个答案:

答案 0 :(得分:0)

您可以使用post_save信号来创建一个信号,如下所示:

    -----> Python app detected

    cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory

    -----> Installing python-3.6.10

    -----> Installing pip

    -----> Installing SQLite3

    Sqlite3 successfully installed.

    -----> Installing requirements with pip

   Collecting appdirs==1.4.3

     Downloading appdirs-1.4.3-py2.py3-none-any.whl (12 kB)

   Collecting asgiref==3.2.5

     Downloading asgiref-3.2.5-py2.py3-none-any.whl (19 kB)

   Collecting asn1crypto==0.24.0

     Downloading asn1crypto-0.24.0-py2.py3-none-any.whl (101 kB)

   Collecting astroid==2.3.3

     Downloading astroid-2.3.3-py3-none-any.whl (205 kB)

   Collecting attrs==17.4.0

     Downloading attrs-17.4.0-py2.py3-none-any.whl (31 kB)

   Collecting Automat==0.6.0

     Downloading Automat-0.6.0-py2.py3-none-any.whl (35 kB)

   Collecting beautifulsoup4==4.8.2

     Downloading beautifulsoup4-4.8.2-py3-none-any.whl (106 kB)

   Collecting blinker==1.4

     Downloading blinker-1.4.tar.gz (111 kB)

   Collecting bs4==0.0.1

     Downloading bs4-0.0.1.tar.gz (1.1 kB)

   Collecting certifi==2019.11.28

     Downloading certifi-2019.11.28-py2.py3-none-any.whl (156 kB)

   Collecting chardet==3.0.4

     Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)

   Collecting click==7.1.1

     Downloading click-7.1.1-py2.py3-none-any.whl (82 kB)

   ERROR: Could not find a version that satisfies the requirement cloud-init==19.4 (from -r /tmp/build_97084a1fb5d789d77fa40f55c1515251/requirements.txt (line 13)) (from versions: none)

   ERROR: No matching distribution found for cloud-init==19.4 (from -r /tmp/build_97084a1fb5d789d77fa40f55c1515251/requirements.txt (line 13))

   Push rejected, failed to compile Python app.

   Push failed

答案 1 :(得分:0)

我们创建AutoFieldNonPrimary并使用如下所示的自定义字段

from django.db.models.fields import AutoField
from django.db.models.fields import checks


class AutoFieldNonPrimary(AutoField):

    def _check_primary_key(self):
        if self.primary_key:
            return [
                checks.Error(
                    "AutoFieldNonPrimary must not set primary_key=True.",
                    obj=self,
                    id="fields.E100",
                )
            ]
        else:
            return []

class YourModel(models.Model):
   auto_field = models.AutoFieldNonPrimary(primary_key=False)