Home > Blockchain >  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

Time:06-04

Here i have two models Keys and Users i am creating POST API so i got encounter with this Error

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 where Keys are stored

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']

Error Encounters:

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

Need Help me to resolve this error, i will be grateful, Thanks

CodePudding user response:

Mukul, you can set null=True and blank=True in the model field which is causing you an error or you can delete the app and create it again with the same code this trick can also work.

But if you do not find solution then you can find several solutions here.

  • Related