-2

So: I'm trying to implement Django CMS to my Django website and I'm facing the "OneToOneField.init() missing 1 required positional argument: 'on_delete'" in my models.py from Django.

from django.db import models


class Word(models.Model):
    word_name = models.CharField(max_length=50)
    word_about = models.TextField()
    word_resources = models.URLField()

    def __str__(self):
        return self.word_name

    class Meta:
        db_table = 'words'


class Principle(models.Model):
    word = models.ForeignKey(Word, on_delete=models.CASCADE)
    principle_name = models.CharField(max_length=100)
    principle_description = models.TextField()

    class Meta:
        db_table = 'principles'


class CodeSnippet(models.Model):
    raw_code = models.TextField()

What I've tried:

this, this + chatgpt

so basically: word = models.OneToOneField(Word, on_delete=models.CASCADE), word = models.OneToOneField(Word, on_delete=models.CASCADE/PROTECT/DO_NOTHING/SET_DEFAULT)

1 Answers1

-1

No, you cannot use on_delete=models.CASCADE with a OneToOneField. The on_delete=models.CASCADE option is not allowed for OneToOneField fields because a OneToOneField represents a unique relationship where each record in the model points to at most one other record.

If you were to use CASCADE as the deletion behavior, it would essentially mean that deleting one record would cause the associated record to be deleted as well, resulting in potential data loss and referential integrity issues.

  • Instead you can use the models.SET_NULL, models.PROTECT, models.SET_DEFAULT with OneToOneField.
  • with Foreign key you can use models.CASCADE.
Bihag Kashikar
  • 1,009
  • 1
  • 2
  • 13
  • Was this answer generated by ChatGPT? It congestive obviously incorrect explanation, `OneToOneField(SomeModel, on_delete=models.CASCADE)` is perfectly legal, as can be seen in [first example from docs](https://docs.djangoproject.com/en/4.2/topics/db/examples/one_to_one/). I also can personally confirm that such definition works fine. The argument about data loss is just weird: you're the developer, and it's your decision whether related models should go away when the source is deleted. In many cases such behavior is desirable. – STerliakov Sep 02 '23 at 17:38