django.db.utils.IntegrityError: NOT NULL constraint failed: app_users.key_value_id

django.db.utils.IntegrityError: NOT NULL constraint failed: app_users.key_value_id

我在这里创建了两个模型密钥和用户 POST API 所以我遇到了这个错误

UserModel.py

class Users(AbstractBaseUser):
       vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
       key_value = models.ForeignKey(KeyTable, on_delete=models.CASCADE, default=None, null=True)
       username = models.CharField(max_length=100, verbose_name="username", unique=True)
       password = models.CharField(max_length=100)
       hardware_id = models.CharField(max_length=150, null=True)
       created_by = models.DateField(verbose_name="created_by", auto_now_add=True)

       USERNAME_FIELD = "username"
       REQUIRED_FIELDS = ['password', 'hardware_id']

       is_active = models.BooleanField(default=True)
       is_admin = models.BooleanField(default=False)
       is_role_vendor = models.BooleanField(default=False)
       is_role_customer = models.BooleanField(default=True)

       def __str__(self):
             return self.username

       objects = UserManager()

KeyModel.py 密钥存储位置

class KeyTable(models.Model):
      key_id = models.IntegerField(unique=True, auto_created=True)
      key_value = models.CharField(max_length=100)
      issue_date = models.DateField(max_length=100)
      expiry_date = models.DateField()
      status = models.CharField(max_length=50)
      license_tenure = models.IntegerField()

      def __str__(self):
          return self.key_value

KeySerializer

class KeySerializer(serializers.ModelSerializer):
    class Meta:
         model: Keys
         fields = ['key_id', 'key_value', 'issue_date', 'expiry_date', 'status', 'license_tenure']

遇到错误:

django.db.utils.IntegrityError: NOT NULL constraint failed: app_users.key_value_id

需要帮助我解决这个错误,我将不胜感激,谢谢

Mukul,您可以在导致错误的模型字段中设置 null=True 和 blank=True 或者您可以删除该应用程序并使用相同的代码重新创建它这个技巧也可以工作。

但是,如果您找不到解决方案,那么您可以找到多种解决方案