How to set ManToManyField to None?

36 Views Asked by At

I have a Section model for storing different sections of laws. A law has Part, Book, Chapter, Title, Section, SubSection, ... and Article

enter image description here

Instead of making models for each of the above parts, I created a section model to store the sections in the database.

The level field in the section model specifies the depth of levels. as you can see in the picture.

class Section(Timestamped):
    parent = models.ManyToManyField(
        to='self',
        verbose_name=_("Parent Section"),
        help_text=_("Specifies the links to another section."),
        blank=True,
        symmetrical=False
    )
    level = models.PositiveIntegerField(
        verbose_name=_("Level of the section"),
    )
    ...

My problem is that when I store the first section or level, the parent should be set to null(which means that the first section has no parent). But I get an error when I set the parent to None.

I have all the sections in a JSON file:

The script for section in sections: section_data = { "text_id": section.get("id"), "level": 1, } section_db, created = Section.objects.get_or_create(**section_data) section_db.parent.add(None)

The error

django.db.utils.IntegrityError: null value in column "to_section_id" of relation "laws_section_parent" violates not-null constraint
DETAIL:  Failing row contains (3, 22, null).

Is there any solution? Are the models correctly designed?

0

There are 0 best solutions below