Home > Net >  django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class
django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class

Time:09-10

So i've been working on a Django-project for a while, and i'm about to finish it. I decided to add a feature to it, and i added a new Foreign key to my model. I made the makemigrations my_app, but when i try to migrate it, this error appears:

django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class_id

This is the model:

class AccountingClass(models.Model):
    name = models.CharField(max_length=150, default="", blank=False)
    
    def __str__(self):  
        return self.name

and this is the Foreign-Key Reference to it:

`accounting_class = models.ForeignKey("AccountingClass", on_delete=models.SET_NULL, default="", blank=False, null=True, help_text="The accounting class of the object")`

What's the problem with this?

CodePudding user response:

It means you have data in your database where accounting class reference does not have the value of type PK. I suspect it is due to the fact that you set default="" which is a string (varchar). This can be completely removed since you have null=True so by default you will have null when there is no reference to the accounting class.

  • Related