Saving a model in Django gives me Warning: Field id doesnt have a default value

2024/9/20 0:29:37

I have a very basic model in Django:

class Case(models.Model):name = models.CharField(max_length=255)created_at = models.DateTimeField(default=datetime.now)updated_at = models.DateTimeField(default=datetime.now)def save(self):if self.created_at == None:self.created_at = datetime.now()self.updated_at = datetime.now()super(Case, self).save()class Meta:db_table = u'cases'

Because I did not specify the PK, Django took care of that for me. I see the field in my database which is called "id", marked as a primary key and auto-increment. I find odd to be getting that warning since everything is cool on the DB and model end. The error is:

_mysql_exceptions.WarningWarning: Field 'id' doesn't have a default value

My work around when saving is to set the id to 0. It kills the warning and the id gets set properly anyway since MySQL handles it.

case = Case()
case.id = 0 #ugly workaround for - Warning: Field 'id' doesn't have a default value
case.name = request.POST[u'case[name]']
case.save()

The issue with this solution is:

  1. It's ugly
  2. The new PK is inaccessible after saving which makes it impossible to serialize properly

Does anyone know how to fix this?

I'm running:

Python 2.7.2
django.VERSION (1, 3, 1, 'final', 0)
mysql  Ver 14.14 Distrib 5.1.45, for apple-darwin10.2.0 (i386) using readline 5.1
MySQL_python-1.2.3-py2.7-macosx-10.4-x86_64.egg

And my create table looks like this:

CREATE TABLE `cases` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,`created_at` datetime NOT NULL,`updated_at` datetime NOT NULL,PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=45 DEFAULT CHARSET=latin1
Answer

I'd like to expand on this question as I've ran into it this week. I was getting this same exact error and taking a look at the model definition and SQL definition showed that:

  1. The models affected either had no PK explicitly defined or had a PK explicitly defined (both had problems). This alone seemed unrelated.

  2. The tables affected had the "id" definition as in the OP, i.e. id int(11) NOT NULL AUTO_INCREMENT. The PRIMARY KEY is set as expected.

  3. Looking into the MySQL query log I got something to this extent:

    INSERT INTO `x` (...) VALUES (...)
    SHOW WARNINGS
    ROLLBACK
    

    Running the query individually is successful, and SHOW WARNINGS reflects the warning noted in the OP.

I however came across a MySQL-end fix, http://webit.ca/2012/01/field-id-doesnt-have-a-default-value/ mentioned that resetting the id definition (which at a cursory glance appears to not be any different) fixes the problem. I can't explain why this works, but it addresses the problem without any additional code changes. I believe this may be in some way linked to removing records, but the whole issue seems non-sensical to me.

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

Related Q&A

Authorization architecture in microservice cluster

I have a project with microservice architecture (on Docker and Kubernetes), and 2 main apps are written in Python using AIOHTTP and Django (also there are and Ingress proxy, static files server, a coup…

fastest way to load images in python for processing

I want to load more than 10000 images in my 8gb ram in the form of numpy arrays.So far I have tried cv2.imread,keras.preprocessing.image.load_image,pil,imageio,scipy.I want to do it the fastest way pos…

How to access server response when Python requests library encounters the retry limit

I am using the Python requests library to implement retry logic. Here is a simple script I made to reproduce the problem that I am having. In the case where we run out of retries, I would like to be ab…

Matplotlib patch with holes

The following code works. The problem is I dont know exactly why it works. The code draws a circle patch (using PathPatch) with a triangle cutout from the centre. My guess is that the inner triangle is…

Convert sha256 digest to UUID in python

Given a sha256 hash of a str in python: import hashlibhash = hashlib.sha256(foobar.encode(utf-8))How can the hash be converted to a UUID? Note: there will obviously be a many-to-one mapping of hexdige…

Drag and Drop QLabels with PyQt5

Im trying to drag and drop a Qlabel on another Qlabel with PyQt5:from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QHBoxLayout, QVBoxLayout, QGridLayout,QFrame, QCo…

replace block within {{ super() }}

I have a base template which includes a block for the default <head> content. Within the head block, theres a block for the <title>.For example, in the base file I would have:<head>{%…

Change Timezone for Date object Python

Hello I am using Pythonanywhere and when I call from datetime import *print date.today().dayIt is printing a different day than the day it is where I live (Austin, Texas). I figured it is because there…

Multiprocessing Pool - how to cancel all running processes if one returns the desired result?

Given the following Python code: import multiprocessingdef unique(somelist):return len(set(somelist)) == len(somelist)if __name__ == __main__:somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5],…

Pandas: Product of specific columns

Finding the product of all columns in a dataframe is easy:df[Product] = df.product(axis=1)How can I specify which column names (not column numbers) to include in the product operation?From the help pa…