0
votes

This is my Models:

from django.db import models
from django.contrib.auth.models import User

class Bookmark(models.Model):
    id = models.PositiveIntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    url = models.URLField()
    isPublic = models.BooleanField(default=True)
    dateTimePosted = models.DateTimeField(auto_now=True,verbose_name="posted at")
    user = models.ForeignKey(User, on_delete=models.CASCADE)

This is my 0001_initials.py:

from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Bookmark',
            fields=[
                ('id', models.PositiveIntegerField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=50)),
                ('url', models.URLField()),
                ('isPublic', models.BooleanField(default=True)),
                ('dateTimePosted', models.DateTimeField(auto_now=True, verbose_name='posted at')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]

When I am inserting values using:

python manage.py shell:
>>from django.contrib.auth.models import User
>>user = User.objects.create_user('test', '[email protected]', 'test@123')
>>from bookmark.models import Bookmark
>>bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user)

this error occurs:

Traceback (most recent call last):

File "", line 1, in

File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method

return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python34\lib\site-packages\django\db\models\query.py", line 394, in create

obj.save(force_insert=True, using=self.db)

File "C:\Python34\lib\site-packages\django\db\models\base.py", line 806, in save

force_update=force_update, update_fields=update_fields)

File "C:\Python34\lib\site-packages\django\db\models\base.py", line 836, in save_base

updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:\Python34\lib\site-packages\django\db\models\base.py", line 922, in _save_table

result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Python34\lib\site-packages\django\db\models\base.py", line 961, in _do_insert

using=using, raw=raw)

File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method

return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1063, in _insert

return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 1099, in execute_sql

cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 80, in execute

return super(CursorDebugWrapper, self).execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute

return self.cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\utils.py", line 94, in exit

six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise

raise value.with_traceback(tb)

File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute

return self.cursor.execute(sql, params)

File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute

return Database.Cursor.execute(self, query, params)

django.db.utils.IntegrityError: NOT NULL constraint failed: bookmark_bookmark.id

how to tackle this error I have deleted database (db.sqlite3)and pycache folder unapplied migrations and then created again using:

python manage.py makemigrations

but still error occurs

1

1 Answers

2
votes

You are not passing the primary key value (id) when you are creating your BookMark object.

Change your create as follows,

bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user, id=<some_int_which_hasnt_been_used>)  # Use an id that you know you hasn't been used.

Now the reason you have to do this is because you have defined your own Primary Key, so Django will not automatically create it for you.

When you do not specify a primary key, Django uses an "id" field which is of type "models.AutoField", and automatically increments the value (without you needing to specify the value for id).

In case you are interested in knowing how it works internally you can read up on Sequences in databases (what Django does internally is create a sequence in your database for the table, and your database has a default value for your id column)

I'm not sure why you have overridden the id field that Django provides automatically (because your id is PositiveIntegerField, and AutoField would generate only positive values anyway), so if there is no specific reason for you defining the PK, I suggest you go with what Django creates for you.