Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - null ForeignKey

I have class SubForum with ForeignKey to self - parent:

class Forum(models.Model):
    name = models.CharField(max_length=200)
    url = models.URLField()

class SubForum(models.Model):
    name = models.CharField(max_length=200)
    orginal_id = models.IntegerField()

    forum = models.ForeignKey('Forum')
    parent = models.ForeignKey('self', null=True, blank=True)

I want to allow for null and blank enteries - I saw examples that this is a proper way to do that.

In sql view everything is ok:

BEGIN;CREATE TABLE "main_forum" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(200) NOT NULL,
    "url" varchar(200) NOT NULL
)
;
CREATE TABLE "main_subforum" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(200) NOT NULL,
    "orginal_id" integer NOT NULL,
    "forum_id" integer NOT NULL REFERENCES "main_forum" ("id"),
    "parent_id" integer
)
;COMMIT;

In parent_id field there is no NOT NULL, but when I want to add new SubForum using admin panel without setting parent i get error:

Cannot assign None: "SubForum.parent" does not allow null values.

What's wrong?

like image 702
pbm Avatar asked Nov 07 '10 10:11

pbm


People also ask

Can ForeignKey be null in Django?

django rest framework - ForeignKey does not allow null values - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What is null true Django?

If a string-based field has null=True , that means it has two possible values for “no data”: NULL , and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL .

What is the difference between null and blank in Django?

null is purely database-related, whereas blank is validation-related. If a field has blank=True , form validation will allow entry of an empty value. If a field has blank=False , the field will be required.


1 Answers

I made some changes, reverted it back and now everything is working fine... and I don't see any difference with code that I posted here...

Should I delete question?

like image 74
pbm Avatar answered Oct 11 '22 05:10

pbm