После makemigrations, затем миграции. Я получил эту ошибку.
IntegrityError: строка в таблице main_post с первичным ключом 2 имеет недопустимый внешний ключ: main_post.author_id имеет значение 1, которое делает не имеет соответствующего значения в auth_user.id
Я пробую некоторые решения в аналогичном вопросе, но он не работает
My models.py
User = get_user_model()
class PostView(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.user.username
class Comment(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
content = models.TextField()
post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField()
def __str__(self):
return self.user.username
class Category(models.Model):
title = models.CharField(max_length=40)
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
detail = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = RichTextUploadingField(config_name='post_ckeditor')
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True)
next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={
'id': self.id
})
def get_update_url(self):
return reverse('post-update', kwargs={
'id': self.id
})
def get_delete_url(self):
return reverse('post-delete', kwargs={
'id': self.id
})
@property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
@property
def view_count(self):
return PostView.objects.filter(post=self).count()
@property
def comment_count(self):
return Comment.objects.filter(post=self).count()
My views.py
#Some code not include in this
def post(request, id):
most_recent = Post.objects.order_by('-timestamp')[:3]
category_count = get_category_count()
post = get_object_or_404(Post, id=id)
PostView.objects.get_or_create(user=request.user, post=post)
form = CommentForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse('post-detail', kwargs={
'id':post.id
}))
context = {
'form': form,
'post': post,
'category_count':get_category_count,
'most_recent': most_recent,
}
return render(request, 'post.html', context)