Deleting related objects deletes the ForeignKey object

Crystal picture Crystal · Feb 8, 2017 · Viewed 8.5k times · Source

I have the following models:

class User(models.Model):
      user_question = models.ForeignKey(UserQuestion)

class Question(models.Model):
      text = models.CharField(max_length=255)

class UserQuestion(models.Model):
      answer = models.CharField(max_length=255)
      question = models.ForeignKey(Question)
      user = models.ForeignKey(User, related_name='questions')

When I run the query below the user model is also deleted

user.questions.all().delete()

Is there any way to delete the questions without deleting the user?

I tried iterating over the questions and that didn't work

questions = user.questions.all()
for an in questions:
     answer.delete()

I thought the queryset was lazy so maybe I needed to evaluate it before deleting so I printed it and this did not work.

print questions
questions.delete()

I know that making the ForeignKey nullable would provide me with methods like clear and remove but I did not want to do this because I did not want any orphaned user questions.

I updated the ForeignKey as follows

class UserQuestion(models.Model):
  answer = models.CharField(max_length=255)
  user = models.ForeignKey(User, related_name='questions', null=True, on_delete=models.SET_NULL)

I ran makemigrations and migrate but when I ran the query below The question model was still deleted.

user.questions.all().delete()

Answer

Or Duan picture Or Duan · Feb 8, 2017
question = models.ForeignKey(Question, related_name='answers', on_delete=models.SET_NULL, null=True)

untested, but should work.

Your issue is a DB related issue, when deleting a foreignkey the DB will try to delete the related row.

Read more on the other options on this great answer.