Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of 'default=True' in BooleanField

I have a simple question: in my model, I am defining the structure for one of my tables; however, I want to set up a default value for the Booleanfield: own, but it does not seem to be working properly. Here is my code in the model:

class Books(models.Model):
    title = models.CharField(max_length=100)
    own = models.BooleanField(default=True)

When I desc my table in mysql, this is what I get (note that own has default Null):

enter image description here

Also, when I try to do the following:

INSERT INTO `counters_books` (`title`) VALUES ('My Brain is Open')

I get this error:

ERROR 1364 (HY000): Field 'own' doesn't have a default value

P.S. I understand that by using NullBooleanField I will be able to solve the problem; however, what's the point of default if I cannot insert a row unless I had to specify a value for that field?

like image 216
Thuglife Avatar asked Jun 25 '13 00:06

Thuglife


1 Answers

default is not handled at the SQL level - it's handled at the model level. Thus, a raw SQL query in your db environment would throw an error. Try this in your Django environment:

>> book_obj = Book('Harry Potter')
>> book_obj.save()

When done at the model level, the default value will be inserted into your SQL DB

like image 76
JcKelley Avatar answered Sep 28 '22 05:09

JcKelley