简体   繁体   中英

NOT NULL constraint failed error in django despite having null set to true and blank set to true

Here's the code:

class community(models.Model):
    communityName = models.CharField(max_length=280)
    communityID = models.BigIntegerField(null=True,blank=True)
    icon = models.CharField(max_length=400)

    def __str__(self):
        return self.communityName

class team(models.Model):
    date = models.DateField()
    startTime = models.TimeField()
    teamName = models.CharField(max_length=280)
    community = models.ForeignKey(community, on_delete=models.CASCADE, default=None)

I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown:

django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id

I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you!

Make it like this in your team model:

community = models.ForeignKey(community, on_delete=models.CASCADE,  blank=True, null=True)

This is the proper way to make it nullable. When you specify default=None , Django ORM does not know if this field is nullable or not. community_id is the field in team model and it is (though syntactically implicit) used to refer community model by the foreign key in team model, and that field was set as not nullable, so that generates IntegrityError , if not set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM