django ForeignKey null = true
It causes no changes to the schema (just clarifying it only creates tables, doesn't modify), but upon syncdb, would create SQL statements without NOT NULL
.
You can check the SQL output of the table definitions via python manage.py sqlall my_app
and see for yourself!
Chris Muench
Updated on June 05, 2022Comments
-
Chris Muench almost 2 years
from django.db import models class Story(models.Model): id = models.IntegerField(primary_key=True) news_type = models.CharField(max_length=255,null=True) category_id = models.CharField(max_length=255,null=True) title = models.CharField(max_length=255,null=True) created = models.DateTimeField(null=True) author = models.CharField(max_length=255, null=True) author_title = models.CharField(max_length=255, null=True) image_caption = models.TextField(null=True) image_credit = models.CharField(max_length=255,null=True) image_full_url = models.CharField(max_length=255,null=True) body = models.TextField(null=True) summary = models.TextField(null=True) video_id = models.CharField(max_length=255,null=True) external_url = models.CharField(max_length=255,null=True) order = models.IntegerField(null=True) class StoryFactBox(models.Model): story = models.ForeignKey('Story', null = True) body = models.TextField() class StoryKeyword(models.Model): story = models.ForeignKey('Story', null = True) keyword = models.CharField(max_length=255)
What schema changes does
models.ForeignKey('Story', null = True)
cause to happen?I am reading from the docs:
I want to use remove() and clear() and this is part of documentation.
In order to prevent database inconsistency, this method only exists on ForeignKey objects where null=True. If the related field can't be set to None (NULL), then an object can't be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn't have null=True, this is invalid.