Why does Django ORM allow me to omit parameters for NOT NULL fields when creating an object?

2024/10/2 22:29:17

Stupid question time. I seem to be able to create an object for a Django model even though I omit a column that was defined as NOT NULL and I don't understand why. Here's my model:

class Movie(models.Model):name = models.CharField(max_length=256)length_minutes = models.IntegerField()rating = models.CharField(max_length=2)class Meta:db_table = 'movies'

When I run python manage.py sql I see:

BEGIN;
CREATE TABLE "movies" ("id" serial NOT NULL PRIMARY KEY,"name" varchar(256) NOT NULL,"length_minutes" integer NOT NULL,"rating" varchar(2) NOT NULL
);
COMMIT;

Also, if I run the command \d movies from the psql, I can see that all columns are designated NOT NULL.

But here's what I don't understand. When I run the Python shell, I can issue the following command and a new row with an empty 'name' column will be created:

Movie.objects.create(length_minutes=120, rating='PG')

However, if I issue (what I believe to be) the equivalent SQL command:

INSERT INTO movies(length_minutes, rating) VALUES(120, 'PG');

... I get the error I would expect: "ERROR: null value... violates not-null constraint."

Why does Django's ORM allow me to create an object that lacks a parameter for a NOT NULL CharField column? Does it assume that I'm using model validators? If so, it seems to be a pretty dumb and trusting ORM.

I'm using Python 2.7.1, Django 1.4, and PostgreSQL 9.1.4.

Thanks for your help.

Answer

After a great deal of online research and experimentation, what I've found indicates that the behavior I described above is normal Django behavior. Apparently, Django doesn't validate models by default. Furthermore, the default value for a CharField is the empty string. In order to ensure that Django raises the expected IntegrityError if I omit a CharField parameter designated NOT NULL, I needed to add "default=None" to the signature declaration:

name = models.CharField(max_length=256, default=None)

Can I get credit for answering my own question?

https://en.xdnf.cn/q/70800.html

Related Q&A

Where should i do the django validations for objects and fields?

Im creating a django application which uses both the Django Rest Framework and the plain django-views as entrypoint for users.I want to do validation both independant fields of my models, and on object…

Why does bytes.fromhex() treat some hex values strangely?

Im trying to use the socket library in Python to send bytes of two hex digits to a piece of hardware programmed to accept them. To create the bytes from a user-entered string of hex digits, Im trying …

Extracting beats out of MP3 music with Python

What kind of solutions are there to analyze beats out of MP3 music in Python? The purpose of this would be to use rhythm information to time the keyframes of generated animation, export animation as v…

Switch to popup in python using selenium

How do I switch to a popup window in the below selenium program. Ive looked up for all possible solutions but havent been able to get my head around them. Please help!!from selenium import webdriver fr…

Segmentation fault while redirecting sys.stdout to Tkinter.Text widget

Im in the process of building a GUI-based application with Python/Tkinter that builds on top of the existing Python bdb module. In this application, I want to silence all stdout/stderr from the consol…

Why do pandas and dask perform better when importing from CSV compared to HDF5?

I am working with a system that currently operates with large (>5GB) .csv files. To increase performance, I am testing (A) different methods to create dataframes from disk (pandas VS dask) as well a…

is there any pool for ThreadingMixIn and ForkingMixIn for SocketServer?

I was trying to make an http proxy using BaseHttpServer which is based on SocketServer which got 2 asynchronous Mixins (ThreadingMixIn and ForkingMixIn)the problem with those two that they work on each…

Python - Read data from netCDF file with time as seconds since beginning of measurement

I need to extract values from a netCDf file. I am pretty new to python and even newer this file format. I need to extract time series data at a specific location (lat, lon). I have found that there is …

PyQt Multiline Text Input Box

I am working with PyQt and am attempting to build a multiline text input box for users. However, when I run the code below, I get a box that only allows for a single line of text to be entered. How to …

Calculate the sum of model properties in Django

I have a model Order which has a property that calculates an order_total based on OrderItems linked by foreign key.I would like to calculate the sum of a number of Order instances order_total propertie…