[Answered ]-Django model throw IntegrityError: (1048, "Column 'xxx' cannot be null") when I want to fill data later

3👍

You have to just create the object in-memory and fill out the data before you try and save it to the database. As far as the database is concerned that row is invalid until everything is filled out.

So:

t = Test(owner=member) # Does not go to the database

#
# some other non-related code
# 

# The you update your Test object with all of the fields and save
t.name = 34
t.score = 4
t.service = service # added separately
t.feel = feel # added separately 
t.save()

-1👍

If you are using a ForeignKey in the instance of get_or_create you need to express whether or not you want to allow it to be null. If not when you try to save it it’s going to give you that error.

I know you said you didn’t want to use NULL ( however, get_or_create it would be required )

You need to set the following in order to use the get_or_create method.

feel = models.ForeignKey(feel, null=True, blank=True, unique=False/True )

I would move away from get or create, and go the route of regularly creating the object.

example.)

object = ModelObject( data = "blah", data2 = "blah" ) 
object.save(commit=False)

# do your other processing
object.other_data = "value"
object.save()

All the best, happy coding.

Jody Fitzpatrick

Leave a comment