SQLAlchemy many-to-many UNIQUE constraint failed association table - sqlalchemy

I connected the tables 'projects' and 'project_freelancer' through a many-to-many relationship, because one project can have multiple freelancer and one freelancer can do multiple projects.
In 'projects' I have only one primary key 'url'.
In 'projects_freelancer' I have a composite primary key out of 'url' and 'freel_url'
Therefore I definded my association table like this:
association_table = Table('association', Base.metadata,
Column('projects_url', ForeignKey('projects.url', ondelete="CASCADE"), primary_key=True),
Column('project_freelancer_url'),
Column('project_freelancer_freel_url'),
ForeignKeyConstraint(
('project_freelancer_url', 'project_freelancer_freel_url'),
('project_freelancer.url', 'project_freelancer.freel_url')),
)
And here are my class-definitions (short version):
class Project(Base):
__tablename__ = "projects"
url = Column(String, primary_key=True)
datetime = Column(DateTime)
children2 = relationship("ProjectFree", secondary=association_table, back_populates='parents2', cascade="all, delete") # Many-to-many relationship
class ProjectFree(Base):
__tablename__ = "project_freelancer"
url = Column(String, primary_key=True)
freel_url = Column(String, primary_key=True)
update = Column(DateTime)
parents2 = relationship("Project", secondary=association_table, back_populates="children2", cascade="all, delete")
When filling my db I get the following error message:
ERROR [21-11-18 09:58:47] scrapy.core.scraper _itemproc_finished :249 Error processing {'added': datetime.datetime(2021, 11, 18, 9, 58, 47, 654089),
'freel_bidtext': 'Hi,\n'
'\n'
'I hope all is well with you.\n'
'\n'
'I have read the job description and finds it a perfect '
'match for me as I have extensive hands-on experience in '
'React JS/Vue JS development.\n'
'\n'
'I have developed a lot of websites and sto',
'freel_country': 'Pakistan',
'freel_deadline': 'in 7 days',
'freel_earnings': '0.0',
'freel_name': 'abdulhaseebbasit',
'freel_price': '$140 USD',
'freel_ranking': 3,
'freel_rating': '0.0',
'freel_reviews': '0',
'freel_url': 'https://www.freelancer.com/u/abdulhaseebbasit',
'update': datetime.datetime(1900, 1, 1, 0, 0),
'url': 'https://www.freelancer.com/projects/javascript/looking-for-react-developer-32135012/?ngsw-bypass=&w=f'}
Traceback (most recent call last):
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\default.py", line 719, in do_execute
cursor.execute(statement, parameters)
sqlite3.IntegrityError: UNIQUE constraint failed: association.projects_url
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\twisted\internet\defer.py", line 858, in _runCallbacks
current.result = callback( # type: ignore[misc]
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\scrapy\utils\defer.py", line 150, in f
return deferred_from_coro(coro_f(*coro_args, **coro_kwargs))
File "C:\Users\myuser\PycharmProjects\crawlerDiss\diss\diss\pipelines.py", line 42, in process_item
return self.handle_ProjectFreelancer(item, spider)
File "C:\Users\myuser\PycharmProjects\crawlerDiss\diss\diss\pipelines.py", line 160, in handle_ProjectFreelancer
session.commit()
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3345, in flush
self._flush(objects)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3485, in _flush
transaction.rollback(_capture_exception=True)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3445, in _flush
flush_context.execute()
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 579, in execute
self.dependency_processor.process_saves(uow, states)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\dependency.py", line 1182, in process_saves
self._run_crud(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\orm\dependency.py", line 1245, in _run_crud
connection.execute(statement, secondary_insert)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1289, in execute
return meth(self, multiparams, params, _EMPTY_EXECUTION_OPTS)
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1845, in _execute_context
self._handle_dbapi_exception(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1802, in _execute_context
self.dialect.do_execute(
File "c:\users\myuser\pycharmprojects\crawlerdiss\venv\lib\site-packages\sqlalchemy\engine\default.py", line 719, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: association.projects_url
[SQL: INSERT INTO association (projects_url, project_freelancer_url, project_freelancer_freel_url) VALUES (?, ?, ?)]
[parameters: ('https://www.freelancer.com/projects/javascript/looking-for-react-developer-32135012/?ngsw-bypass=&w=f', 'https://www.freelancer.com/projects/javascript/looking-for-react-developer-32135012/?ngsw-bypass=&w=f', 'https://www.freelancer.com/u/abdulhaseebbasit')]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
In the db-browser I can see, that only unique combinations are filled into the association table. So for a project already in the association table, with a different freelancer the error occurs. Do you have an idea what I have to change? Should I change the unique behavior anywhere?

Finally I get the solution and it was quite easy (as is so often the case). In the association table, I had to add , primary_key = True for each Foreign Key. Here is the final association_table:
association_table = Table('association', Base.metadata,
Column('projects_url', ForeignKey('projects.url', ondelete="CASCADE"), primary_key=True),
Column('project_freelancer_url', primary_key = True),
Column('project_freelancer_freel_url', primary_key = True),
ForeignKeyConstraint(
('project_freelancer_url', 'project_freelancer_freel_url'),
('project_freelancer.url', 'project_freelancer.freel_url')),
)
The idea come to my mind by reading the documentations tip here.

Related

How to solve a duplicate column name error in web2py

I'm running web2py on pythonanywhere. I've started getting a duplicate column name error when the db.py file runs. I've tried restoring the database from a backup and also dropping the table and adding it back, without success. At this point I'm completely locked out of my app.
I've tried removing all but the last field in the table, but then the problem appears in the next table.
I'm wondering if web2py uses a cache that needs to be cleared.
Here is the relevant portion of my db.py file:
db.define_table('library',
Field('title', 'string'),
Field('created','datetime'),
Field('duration','float'),
Field('error_message','string'),
Field('external_id','string'),
Field('hosting_type','string'),
Field('source_id','string', unique = True),
Field('last_modified','datetime'),
Field('media_type','string'),
Field('mime_type','string'),
Field('relationships','string'),
Field('source_schema','string'),
Field('source_url','string'),
Field('status','string'),
Field('trim_in_point','string'),
Field('trim_out_point','string'),
Field('source_type','string'),
Field('poster','string'),
Field('background_poster_filename','string'),
Field('background_poster','upload', required=False, requires = IS_EMPTY_OR(IS_IMAGE(extensions=('png', 'jpg', 'jpeg'), maxsize=(1920, 1080)))),
Field('sources','list:string',length = 4096),
Field('tracks','string'),
singular="Library",
plural="Library"
)
Here is the error ticket:
Ticket ID
67.0.14.100.2022-06-23.16-49-09.ecf75fd3-1bb4-4f76-b557-95e072c6681f
<class 'gluon.contrib.pymysql.err.InternalError'> (1060, "Duplicate column name 'title'")
Version
web2py™ Version 2.21.1-stable+timestamp.2020.11.28.04.10.44
Python Python 3.7.10: /usr/local/bin/uwsgi (prefix: /home/ghdev/.virtualenvs/ghdevvirtualenv)
Traceback
Traceback (most recent call last):
File "/home/ghdev/web2py/gluon/restricted.py", line 219, in restricted
exec(ccode, environment)
File "/home/ghdev/web2py/applications/ghrokucms/models/db.py", line 283, in <module>
plural="Library"
File "/home/ghdev/web2py/gluon/packages/dal/pydal/base.py", line 660, in define_table
table = self.lazy_define_table(tablename, *fields, **kwargs)
File "/home/ghdev/web2py/gluon/packages/dal/pydal/base.py", line 701, in lazy_define_table
polymodel=polymodel,
File "/home/ghdev/web2py/gluon/packages/dal/pydal/adapters/base.py", line 920, in create_table
return self.migrator.create_table(*args, **kwargs)
File "/home/ghdev/web2py/gluon/packages/dal/pydal/migrator.py", line 376, in create_table
fake_migrate=fake_migrate,
File "/home/ghdev/web2py/gluon/packages/dal/pydal/migrator.py", line 544, in migrate_table
self.adapter.execute(sub_query)
File "/home/ghdev/web2py/gluon/packages/dal/pydal/adapters/__init__.py", line 69, in wrap
return f(*args, **kwargs)
File "/home/ghdev/web2py/gluon/packages/dal/pydal/adapters/base.py", line 468, in execute
rv = self.cursor.execute(command, *args[1:], **kwargs)
File "/home/ghdev/web2py/gluon/contrib/pymysql/cursors.py", line 166, in execute
result = self._query(query)
File "/home/ghdev/web2py/gluon/contrib/pymysql/cursors.py", line 322, in _query
conn.query(q)
File "/home/ghdev/web2py/gluon/contrib/pymysql/connections.py", line 835, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/ghdev/web2py/gluon/contrib/pymysql/connections.py", line 1019, in _read_query_result
result.read()
File "/home/ghdev/web2py/gluon/contrib/pymysql/connections.py", line 1302, in read
first_packet = self.connection._read_packet()
File "/home/ghdev/web2py/gluon/contrib/pymysql/connections.py", line 981, in _read_packet
packet.check_error()
File "/home/ghdev/web2py/gluon/contrib/pymysql/connections.py", line 393, in check_error
err.raise_mysql_exception(self._data)
File "/home/ghdev/web2py/gluon/contrib/pymysql/err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
gluon.contrib.pymysql.err.InternalError: (1060, "Duplicate column name 'title'")
I'm at a loss to figure how to resolve this. Any help would be greatly appreciated.
Thanks.
I solved this problem. In addition to dropping the table, I needed to delete the associated file in the web2py database directory. I then had to manually add back the table to the mySql database.
SOLVED.

I'm getting django.db.utils.IntegrityError: FOREIGN KEY constraint failed in cmd

I copied a json file from online. I'm using it for django project.
I entered the following lines in cmd -
>>> import json
>>> from blog.models import Post
>>> with open('posts.json') as f:
... posts_json=json.load(f)
...
>>> for post in posts_json:
... post = Post(title=post['title'], content=post['content'], author_id=post['
user_id'])
... post.save()
...
And the error I got was -
Traceback (most recent call last):
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 3, in <module>
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 782, in save_base
updated = self._save_table(
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields
, raw)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 924, in _do_insert
return manager._insert(
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\sql\compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
This is my models.py file -
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title=models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
This is the json file I copied from online https://raw.githubusercontent.com/CoreyMSchafer/code_snippets/master/Django_Blog/snippets/posts.json
This is a later reply but maybe it will help someone else in the future.
I had the same issue now and the same code and posts.json as well, it seems that in posts.json the user_id it either 1 or 2 so the error means that there is no user with id 1 or 2 in your database.
I would say that there is no user with id = 2 I supposed you have created a superuser which is id = 1 and if you create a second user it may not take id = 2, so you need to find out what is that id and change it in your posts.json file.
That's how I just fixed my problem.
Sorry for my English.
The only foreign key here is author, so a foreign key constraint failing must mean that there's no user with an id corresponding to the user_id field in a record in that data.
Since by a quick glance it looks like there's only user ids 1 and 2, make sure you have those two users in your database, then try again.

The database backend does not accept 0 as a value for AutoField

I have a model:
class Tour(models.Model):
INACTIVE = 0
ACTIVE = 1
ARCHIVE = 2
STATUS = (
(INACTIVE, "Inactive"),
(ACTIVE, "Active"),
(ARCHIVE, "Archive"),
)
AIR_TOUR = 0
GROUND_TOUR = 1
SEA_TOUR = 2
T_TYPES = (
(AIR_TOUR, "Air_tour"),
(GROUND_TOUR, "Ground_tour"),
(SEA_TOUR, "Sea_tour"),
)
title = models.CharField(max_length=200)
tour_from = models.ForeignKey(Airport, related_name='from_location')
tour_to = models.ForeignKey(Airport, related_name='to_location')
duration_day = models.IntegerField(default=1, blank=True, null=True)
duration_night = models.IntegerField(default=1, blank=True, null=True)
transport_type = models.IntegerField(default=AIR_TOUR, choices=T_TYPES, blank=True, null=True)
documents = models.TextField(default='', blank=True, null=True)
description = models.TextField(blank=True, null=True, default='')
services = models.TextField(blank=True, null=True, default='')
airline = models.ForeignKey(Airline, null=True, blank=True)
train = models.ForeignKey(Train, null=True, blank=True)
bus = models.ForeignKey(Bus, null=True, blank=True)
user = models.ForeignKey(User, related_name='user')
creator = models.ForeignKey(User, related_name='creator')
status = models.IntegerField(default=INACTIVE, choices=STATUS, blank=True, null=True)
create_at = models.DateTimeField(default='2000-10-10')
update_at = models.DateTimeField(default='2000-10-10')
I try to change status to ARCHIVE by this code:
test = Tour.objects.get(id=self.kwargs['pk'])
test.status = ARCHIVE
test.save()
and get this error:
The database backend does not accept 0 as a value for AutoField.
status field is not AutoField. Why this error happend?
UPDATE:
full stack trace:
Django version 1.11, using settings 'project.settings_local'
Starting development server at http://0.0.0.0:8888/
Quit the server with CONTROL-C.
Internal Server Error: /dashboard/tour/delete/1/
Traceback (most recent call last):
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/py/project/dashboard/views_tour.py", line 196, in post
tour.save()
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "/home/.virtualenvs/project/lib/python3.6/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 "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 903, in _save_table
forced_update)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 953, in _do_update
return filtered._update(values) > 0
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/query.py", line 661, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1191, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql
sql, params = self.as_sql()
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1157, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/related.py", line 963, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save
prepared=False)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 955, in get_db_prep_value
value = connection.ops.validate_autopk_value(value)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 155, in validate_autopk_value
raise ValueError('The database backend does not accept 0 as a '
ValueError: The database backend does not accept 0 as a value for AutoField.
Internal Server Error: /dashboard/tour/delete/1/
Traceback (most recent call last):
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/py/project/dashboard/views_tour.py", line 196, in post
tour.save()
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "/home/.virtualenvs/project/lib/python3.6/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 "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 903, in _save_table
forced_update)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/base.py", line 953, in _do_update
return filtered._update(values) > 0
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/query.py", line 661, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1191, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql
sql, params = self.as_sql()
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1157, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/related.py", line 963, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save
prepared=False)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 955, in get_db_prep_value
value = connection.ops.validate_autopk_value(value)
File "/home/.virtualenvs/project/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 155, in validate_autopk_value
raise ValueError('The database backend does not accept 0 as a '
ValueError: The database backend does not accept 0 as a value for AutoField.
You likely have a foreign key field that contains a 0 (instead of null, or a valid value). If you don't have the proper foreign key constraints at the DB level (or you turned off foreign key checks when you added the constraints), there is nothing preventing invalid foreign key references from existing in that row.
Check the data in the all your foreign key fields for a 0: tour_from, tour_to,
airline, train, bus, user, creator.
What you're doing should work. Since the object is already in the database, it's strange that updating it with the same fields leads to a 0 somewhere (probably one of the foreign keys).
You should debug this and there are two ways to go at it:
Inspect your database using raw SQL. manage.py dbshell opens a SQL shell where you can do SELECT * FROM my_app_tour WHERE id = 1. Look at the particular row, maybe you can spot the issue.
Try test.save(update_fields=['status']). If that works, add more fields to update one by one, e.g. test.save(update_fields=['status', 'tour_from'], then test.save(update_fields['status', 'tour_from', 'tour_to'])... until the error is thrown again.
I suspect a database corruption, but there might be some other more serious issue in the way you create the objects. That would cause problems down the line.
Check your django_content_type table, look for 0's in the id column. Django logs database operations after each call, and it writes the ID of the content type.
I found that I had several entries with a 0 id. Updating these with unique numbers after the end of the sequence and restarting Django fixed this for me.
Honestly, I have no idea how it got that way. I'm using Django 2.2.

Error while using INSERT INTO table ON DUPLICATE KEY, using a for loop array

I am working on updating a mysql database using pyspark framework, and running on AWS Glue services.
I have a dataframe as follows:
df2= sqlContext.createDataFrame([("xxx1","81A01","TERR NAME 55","NY"),("xxx2","81A01","TERR NAME 55","NY"),("x103","81A01","TERR NAME 01","NJ")], ["zip_code","territory_code","territory_name","state"])
# Print out information about this data
df2.show()
+--------+--------------+--------------+-----+
|zip_code|territory_code|territory_name|state|
+--------+--------------+--------------+-----+
| xxx1| 81A01| TERR NAME 55| NY|
| xxx2| 81A01| TERR NAME 55| NY|
| x103| 81A01| TERR NAME 01| NJ|
+---------------------------------------------
I have a primary key ZIP_CODE, and I need to ensure, there is no duplicate keys, or primary key exceptions, and hence am using INSERT INTO .... ON DUPLICATE KEYS.
And since I have more than one rows to insert/update, I have used for array in python to loop through the records, and perform INSERT into database. The code is as follows:
sarry = df2.collect()
for r in sarry:
db = MySQLdb.connect("xxxx.rds.amazonaws.com", "username", "password",
"databasename")
cursor = db.cursor()
insertQry=INSERT INTO ZIP_TERR(zip_code, territory_code, territory_name,
state) VALUES(r.zip_code, r.territory_code, r.territory_name, r.state) ON
DUPLICATE KEY UPDATE territory_name = VALUES(territory_name), state =
VALUES(state);"
n=cursor.execute(insertQry)
db.commit()
db.close()
When running the above insert query function, I am getting the following error message, couldn't get any clue on the error. Please help.
Traceback (most recent call last):
File "/tmp/zeppelin_pyspark-2291407229037300959.py", line 367, in <module>
raise Exception(traceback.format_exc())
Exception: Traceback (most recent call last):
File "/tmp/zeppelin_pyspark-2291407229037300959.py", line 360, in <module>
exec(code, _zcUserQueryNameSpace)
File "<stdin>", line 8, in <module>
File "/usr/local/lib/python2.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/local/lib/python2.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/local/lib/python2.7/site-packages/pymysql/connections.py", line 893, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/local/lib/python2.7/site-packages/pymysql/connections.py", line 1103, in _read_query_result
result.read()
File "/usr/local/lib/python2.7/site-packages/pymysql/connections.py", line 1396, in read
first_packet = self.connection._read_packet()
File "/usr/local/lib/python2.7/site-packages/pymysql/connections.py", line 1059, in _read_packet
packet.check_error()
File "/usr/local/lib/python2.7/site-packages/pymysql/connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python2.7/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
InternalError: (1054, u"Unknown column 'r.zip_code' in 'field list'")
If i simply try to print the values for one row, am getting the values printed as follows:
print('zip_code_new: ', r.zip_code, r.territory_code, r.territory_name, r.state)
zip_code_new: xxx1 81A01 TERR NAME 55 NY
Thanks. I am working on AWS Glue/Pyspark, so I need to use native python libraries.
The following insert query works, with a for loop.
insertQry="INSERT INTO ZIP_TERR(zip_code, territory_code, territory_name, state) VALUES(%s, %s, %s, %s) ON DUPLICATE KEY UPDATE territory_name = %s, state = %s;
n=cursor.execute(insertQry, (r.zip_code, r.territory_code, r.territory_name, r.state, r.territory_name, r.state))
print (" CURSOR status :", n)
Result output:
CURSOR status : 2
Thanks. Hope this will be of reference to others.

ProgrammingError - sqlalchemy - on_conflict_do_update

Following this question:
As Ilja Everilä mentioned in his answer, I created a table object:
from sqlalchemy import *
metadata = MetaData()
idTagTable = Table('id_tag', metadata,
Column('id', String(255), primary_key = True),
Column('category', String(20), nullable = False),
Column('createddate', Date, nullable = False),
Column('updatedon', Date, nullable = False)
)
After creating a table object, I changed insert and update statements:
insert_statement = sqlalchemy.dialects.postgresql.insert(idTagTable)
upsert_statement = insert_statement.on_conflict_do_update(
constraint=PrimaryKeyConstraint('id'),
set_={"updatedon": insert_statement.excluded.updateon,
"category":insert_statement.excluded.category}
)
insert_values = df.to_dict(orient='records')
conn.execute(upsert_statement, insert_values)
Now I am getting Programming Error:
Traceback (most recent call last):
File "<ipython-input-66-0fc6a1bf9c6b>", line 7, in <module>
conn.execute(upsert_statement, insert_values)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _execute_context
context)
File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 467, in do_executemany
cursor.executemany(statement, parameters)
ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near
")"
LINE 1: ...category) VALUES ('sports') ON CONFLICT () DO UPDAT...
^
Not Able to understand why I am getting this error.
The PrimaryKeyConstraint object you're using as constraint= argument is not bound to any table and would seem to produce nothing when rendered, as seen in ON CONFLICT (). Instead pass the primary key(s) of your table as the conflict_target and Postgresql will perform unique index inference:
upsert_statement = insert_statement.on_conflict_do_update(
constraint=idTagTable.primary_key,
set_={"updatedon": insert_statement.excluded.updateon,
"category":insert_statement.excluded.category}
)