简体   繁体   English

没有Null约束失败-null =已设置真

[英]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. 我要实现的是要建立一个关系,其中Register模型可以具有0到许多位置。

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. 我已经进行了makemigrations,如果再次运行它,则表明没有任何更改。

"NOT NULL constraint failed: register_register.locations_id" “ NOT NULL约束失败: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. 我一直在搜索其他帖子,它建议添加我已添加的null = True参数,但仍然出现此错误。 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. 使用manage.py flush从数据库中清除数据使我能够重新迁移项目。

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. 我意识到我在关系上犯了一个错误,并且外键在错误的桌子上,它必须放在适当的位置,因此从根本上讲是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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