[Fixed]-Django showing error while saving data into a model: django.db.utils.IntegrityError: (1048, "Column 'id' cannot be null")

1👍

Well I’m not sure did you use django migrations, but it won’t let you create this kind of model in django, where your id property (in model) hasn’t primary key as its parameter (mySQL). So why don’t you just define:

class Graphite(models.Model):   

    class Meta:
        db_table = 'graphite'           

    id = models.BigIntegerField(primary_key=True)
    full_name = models.CharField(max_length=250, null=True)
    email = models.CharField(max_length=250, null=True)
    status = models.CharField(max_length=150, null=True)

so set primary_key on id? Then you wouldn’t have to pass id when creating Graphite.

BUT

If you have to provide id which is something you need to have in every Graphite model and it’s something different than primary key, then just define it different, let’s say row_id. But you should still have at last one id property in your model with primary_key set to True when you want to have id as BigIntegerField.

EDIT (on the example)

In mySQL execute this command:

ALTER TABLE graphite ADD COLUMN row_id BIGINT;

Then your model should looks like this:

class Graphite(models.Model):   

    class Meta:
        db_table = 'graphite'           

    row_id = models.BigIntegerField()
    full_name = models.CharField(max_length=250, null=True)
    email = models.CharField(max_length=250, null=True)
    status = models.CharField(max_length=150, null=True)

And usage:

Graphite.objects.using('database_name').create(
  row_id=row['id'],
  full_name=row['full_name'],
  email=row['email'],
  status=row['status'])

and that’s it.

👤turkus

0👍

The problem is that you do not have a primary key.

From the docs:

Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

So, you have to make your id field a primary key by adding primary_key=True. Then, it won’t complain.

0👍

You are overriding id from default django table id.

so there is no id for primary key. Just make it primary=True. or use another id like graphaite_id

0👍

You are missing your primary key, make sure you have your primary=True and to store your id make another column for it

Leave a comment