django.db.utils.IntegrityError: duplicate key value violates unique constraint - django

I have Country model
from django.db import models
class Country(models.Model):
country = models.CharField(max_length = 20, primary_key=True)
country_id = models.IntegerField()
I uploaded some data in Country table with following custom management command
from django.core.management.base import BaseCommand, CommandError
from data.models import Country
import json
from .extract_country import extracting
get_parsed_json = extracting()
def store_data():
for key, value in get_parsed_json['api']['countries'].items():
country_id_field = key
country_name = value
One_country = Country.objects.create(country_id = country_id_field , country = country_name)
One_country.save()
print(One_country)
class Command(BaseCommand):
def handle(self, **options):
extracting()
store_data()
Now i am trying to upload to the Country table extended data which contain the same countries and another but when i am trying to upload data i get the following error. Here is my full traceback
Traceback (most recent call last):
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "data_co
untry_name_04df4fc7_uniq"
DETAIL: Key (country)=(Algeria) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
output = self.handle(*args, **options)
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 23, in handle
store_data()
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 14, in store_data
One_country = Country.objects.create(country_id = country_id_field , country
= country_name)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 718, in save
force_update=force_update, update_fields=update_fields)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 831, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 869, in _do_insert
using=using, raw=raw)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 1136, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\sql\co
mpiler.py", line 1289, in execute_sql
cursor.execute(sql, params)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 100, in execute
return super().execute(sql, params)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\utils.py", li
ne 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "
data_country_name_04df4fc7_uniq"
DETAIL: Key (country)=(Algeria) already exists.
I found that is very frequent problem for django users but didnt find how to fix it. Any suggestions ?

Seems that you try to create County with same county name as it's your primary key.
Try to use get_or_create():
def store_data():
for key, value in get_parsed_json['api']['countries'].items():
country_id_field = key
country_name = value
one_country, created = Country.objects.update_or_create(
country_id=country_id_field
defaults={'country': country_name},
)
# one_country.save() <- no need to save after create or get_or_create method.
print(one_country)

The primary key must be unique, if there is an instance with the key "Algeria" already exists, you cannot create a second instance with the same key.
Instead of:
One_country = Country.objects.create(country_id = country_id_field , country = country_name)
You could use get_or_create:
# ...
One_country, created = Country.objects.get_or_create(country=country_name)
One_country.country_id = country_id_field
One_country.save()
# ...

Related

Django doesn't create test database when running test

I read in Django document that a blank database will be created for testing. I am new to Django so I barely changed anything in setting.py and currently using Sqlite database. However, when I run python manage.py test, Django keep telling the user has been existed, so I tried changing the username for the created users in TestCase, run the test again and found out that the new users are created in the existing database. The test file is as bellow:
class UserTestCase(unittest.TestCase):
def setUp(self):
admin = User.objects.create(username="admin", password="1")
user1 = User.objects.create(username="user1", password="1")
user2 = User.objects.create(username="user2", password="1")
admin.following.add(user1)
admin.followers.add(user2)
def test_users_count(self):
self.assertEqual(User.objects.count()==3)
My model is as bellow:
class User(AbstractUser):
followers = models.ManyToManyField('self', related_name="following", symmetrical=False, through='Follow', through_fields=('followee', 'follower'))
def __str__(self):
return f"{self.username}"
def serialize(self):
return {
"id": self.id,
"username": self.username,
}
class Follow(models.Model):
followee = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
follower = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
def clean(self, *args, **kwargs):
if self.follower__id == self.followee__id:
raise ValidationError('Can not follow self.')
return super().clean(*args, **kwargs)
class Meta:
constraints = [
models.UniqueConstraint(fields=['follower', 'followee'], name='follow_once'),
models.CheckConstraint(check=~Q(follower=F('followee')), name='not_follow_self')
]
EDIT: Bellow is the output when I run python manage.py test
(env_web) PS C:\Users\HL94NVT\Programming\web_development\project4> python manage.py test
System check identified no issues (0 silenced).
EE
======================================================================
ERROR: test_following_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
======================================================================
ERROR: test_users_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
----------------------------------------------------------------------
Ran 2 tests in 0.063s
Using django.test.TestCase instead of unittest.TestCase helps according to the document
https://docs.djangoproject.com/en/3.1/topics/testing/overview/
If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.
Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.

Django | Factory boy | faking a boolean field | django.db.utils.DataError: value too long for type character varying(1)

I am trying to use factory boy to generate fake entries but I'm stepping on an issue related with the boolean field.
Follows the Model and ModelFactory:
# models.py
class Record(models.Model):
date_creation = models.DateTimeField()
rec_type = models.CharField(max_length=1, choices=RECORD_TYPES)
direction = models.BooleanField()
# factories.py
class RecordFactory(DjangoModelFactory):
class Meta:
model = Record
date_creation = factory.Faker('date_time')
rec_type = factory.Faker('random_choices', elements=[x[1] for x in Record.RECORD_TYPES])
direction = factory.Faker('pybool')
How do I fix this issue? Seems to be related with the boolean field.
/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1427: RuntimeWarning: DateTimeField Record.date_creation received a naive datetime (1
977-11-24 14:21:26) while time zone support is active.
RuntimeWarning)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(1)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 30, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/app/iur/core/management/commands/seed.py", line 60, in handle
self.create(options["records"], RecordFactory)
File "/app/iur/core/management/commands/seed.py", line 47, in create
factory_class.create()
File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 564, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "/usr/local/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
return super(DjangoModelFactory, cls)._generate(strategy, params)
File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
return step.build()
File "/usr/local/lib/python3.7/site-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/usr/local/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
return self.factory._create(model, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/factory/django.py", line 185, in _create
return manager.create(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1335, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: value too long for type character varying(1)
It might not be the boolean field that cause the error but
rec_type = models.CharField(max_length=1, choices=RECORD_TYPES)
As it's max_length is 1. Can you confirm that RECORD_TYPES are max 1 character?
django.db.utils.DataError: value too long for type character varying(1)
This should indicate that it's a VARCHAR of max length 1. And from what I can see from the trace, you're db backend is postgres where there is a native boolean field.
The major issue was that I was using the wrong Faker. This one did what I expected:
# factories.py
...
rec_type = factory.Faker('random_element', elements=[x[0] for x in Record.RECORD_TYPES])
...
Just set e.g. direction = False in RecordFactory. Or, if you want to use faker, you can do direction = Faker().pybool()
I think the error is telling you that your DB backend uses a one letter varchar for representing booleans (most probably "t" and "f").

Django: Trying to make Users migration with a self-referential default value

I'm trying to set a default value on a field I added to my User model, but I'm having to do a lot of acrobativs to make it work.
I want to add an 'identifier' SlugField with a default value defined in a function, like so:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
if not User.objects.filter(identifier=identifier).exists():
return identifier
class User(AbstractUser):
identifier = models.SlugField(default=create_identifier, max_length=16)
def __str__(self):
return self.username
This exact scenario works fine on a different (not User) nodel class, but when I try to run migrations with this code for User, I get:
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model
if isinstance(cls().is_anonymous, MethodType):
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/base.py", line 469, in __init__
val = field.get_default()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
File "/home/myprojectname/myprojectname/myprojectname/users/models.py", line 34, in create_identifier
if not User.objects.filter(identifier=identifier).exists():
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/query.py", line 715, in exists
return self.query.has_results(using=self.db)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/query.py", line 509, in has_results
return compiler.has_results()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1037, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1068, in execute_sql
cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."iden...
I have to manually modify the migrations as such:
migrations.CreateModel(
name='User',
fields=[
...
('identifier', models.SlugField(default='', max_length=16)),
...
),
migrations.AlterField(
model_name='user',
name='identifier',
field=models.SlugField(default=myprojectname.users.models.create_identifier, max_length=16),
),
And then if I initially set default='' in the models.py and run migrations it works, and I can change back to default=create_identifier after the fact.
class User(AbstractUser):
identifier = models.SlugField(default='', max_length=16)
def __str__(self):
return self.username
Is there any way I can make this work without having to go through these measures?
Edit: Would I be better off just leaving blank=True, null=True and overriding the model's save() method to change the value if the field is blank or null?
I seem to have solved the issue by modifying create_identifier to the following:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
try:
present = User.objects.first()
except:
present = None
if present:
if not User.objects.filter(identifier=identifier).exists():
return identifier
else:
return identifier

Django Rest Framework - IntegrityError: null value in column "user_id" violates not-null constraint

I am new to Django, want to create custom user models as follows:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
class UniservedTeam(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True)
ContactNumber = models.CharField(max_length=100)
In shell I am trying to create an user :
>>> user = User.objects.create(email='piyush#uniserved.com',password='Piyush#123',username='Piyush#24',last_name='Wanare',first_name='Piyush',is_active=True)
>>> user
<User: Piyush#24>
>>> user.id
1
>>> team = UniservedTeam.objects.create(id=user.id,Role=['Vendor Co-ordinator'],ContactNumber='862339798167')
Getting Error as follows:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 812, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 851, in _do_insert
using=using, raw=raw)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
IntegrityError: null value in column "user_id" violates not-null constraint
I think what you want instead after you make your user is this
team = UniservedTeam.objects.create(user=user,Role=['Vendor Co-ordinator'],ContactNumber='862339798167')
Try this,
team = UniservedTeam.objects.create(user__id=user.id, Role=['Vendor Co-ordinator'],ContactNumber='862339798167')

IntegrityError when saving Django inherited model with custom ID field

I get an error when saving the model with custom primary key - id field.
My model:
class TestZ(models.Model):
id = models.CharField(primary_key=True, max_length=7)
field0 = models.CharField(max_length=10)
class Meta:
abstract = True
class TestX(TestZ):
field1 = models.CharField(max_length=10)
class TestA(TestX):
field2 = models.CharField(max_length=10)
class TestB(TestX):
pass
Error:
>>> TestB.objects.create(pk='aa', field0='0', field1='1')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 157, in create
return self.get_queryset().create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 322, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 687, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1514, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 903, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 451, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: NOT NULL constraint failed: myapp_testb.testx_ptr_id
Without custom pk field in TestZ I can save objects.
From admin page I can add an objects, there are no errors.
Django==1.6.5
You need to reference the custom id field when creating the model object. I tested this out and it works --> TestB.objects.create(id='aa', field0='0', field1='1')