简体   繁体   中英

Not Null Constraint Failed - null=True already set

I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations.

Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register.

My model now looks like:

class Register(AbstractBaseUser, models.Model):
    username = models.CharField(max_length=20,default='',blank=True)
    password = models.CharField(max_length=80,default='',blank=True)
    email = models.CharField(max_length=255,default='',blank=True)
    #Added 2nd May
    #locations = models.ManyToManyField(Location)
    #3rd May change to foreign key
    locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='')

    USERNAME_FIELD = 'username'

The model referenced is:

class Location(models.Model):
    locationname = models.CharField(max_length=80,default='',blank=True)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')

When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes.

"NOT NULL constraint failed: register_register.locations_id"

I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.

Purging the data from the database using manage.py flush allowed me to re-migrate the projects.

I realised that I had made a mistake with the relationship and had the Foreign key on the wrong table, it needed to be on location so that was fundamentally the issue.

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