Reputation: 195
I see this error when I run my code:
NOT NULL constraint failed: blog_post.category_id
Here is the code:
class Post(models.Model):
class Meta:
verbose_name='Запись'
verbose_name_plural='Записи'
author = models.ForeignKey('auth.User')
category = models.ForeignKey('Theme', default=None, blank=True, null=True)
title = models.CharField(max_length=200,verbose_name='Заголовок')
text = RichTextField(verbose_name='Текст')
created_date = models.DateTimeField(verbose_name='Время создания',default=timezone.now)
published_date = models.DateTimeField(verbose_name='Время публикации',blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def approved_commentimages(self):
return self.comments.filter(approved_comment=True)
def __str__(self):
return self.title
class Theme(models.Model):
class Meta:
verbose_name='Категория'
verbose_name_plural='Категории'
title = models.CharField(verbose_name='Заголовок', max_length=40)
slug = models.SlugField(verbose_name='Транслит', null=True)
def __str__(self):
return self.title
What am I do wrong?
Upvotes: 1
Views: 1960
Reputation: 11450
This can happen if you delete or modify migration files, your actual database can get out of sync with your model files and when you run makemigrations
it might say no changes detected, even though the file is different from the actual database.
You can verify this by logging into your MySQL database and check the actual null constraints. You will see that it probably says that it can't be null even though your file say it can.
The easiest solution to this is to just create a new database and run migrate
. However if you already have a lot of data in your database and want to avoid making a new one and migrating your data, you can try to sync the database with your model again manually.
Upvotes: 3