SQLAlchemy insert - AttributeError: Object has no attribute 'items'


spherical

I have a msyql table with a datetime column. I'm trying to use python's datetime.datetime.now() and insert into it using sqlalchemy core.

from sqlalchemy import MetaData, create_engine, Table, insert 
import datetime 
# from sqlalchemy.sql import func
engine = create_engine('...') 
conn = engine.connect() 

tablemeta = MetaData(bind=engine, reflect=True) 

datetime_test_table = Table('datetime_test', tablemeta, autoload=True, 
        autoload_with=engine) 

ins = insert(datetime_test_table).values(datetime.datetime.now()) 
conn.execute(ins)

I get the following error:

AttributeError: 'datetime.datetime' object has no attribute 'items'

I also tried to use func.now(), but a similar error occurs. Which object should I use for inserting?

super shot

Start with documentationInsert.values()

To pass a value to a INSERTstatement, you can use the keyword args:

users.insert().values(name="some name")

Alternatively, you can pass a positional arg:

A dictionary, tuple or list of dictionaries or tuples can be passed as a single positional argument

users.insert().values({"name": "some name"})  # passing a single dict
users.insert().values((5, "some name"))  # passing a tuple (could be list too).

For a tuple/list of values, SQLAlchemy will convert it to a dictionary by iterating over the collection of table columns and values. Here 's a function that processes a single positional arg as .values()( permalink ) :

def process_single(p):
    if isinstance(p, (list, tuple)):
        return dict(
            (c.key, pval)
            for c, pval in zip(self.table.c, p)
        )
    else:
        return p  # this is where it is assumed that your datetime object is a dict

So, for the record, your single positional args .values()can be either or dict, and in the above function, you can see that if you pass the value of or , they are converted to . If your single positional arg is not a or , simply return it assuming it is a (in the example above I have commented where this assumption is made).listtuplelisttupledictlisttupledict

This is what is causing your error. You're passing a positional arg instead .values()of an listor tuple, so SQLAlchemy assumes it's one dict. However, this is not dictan datetime.datetimeinstance , but an instance. mistake...

AttributeError: 'datetime.datetime' object has no attribute 'items'

...just the first time SQLAlchemy performs a specific action on the parameter object , dictafter assuming that SQLAlchemy is a parameter dict.

To solve your problem, just pass the value in an acceptable format, any of them will work:

ins = insert(datetime_test_table).values((datetime.datetime.now(),))
ins = insert(datetime_test_table).values([datetime.datetime.now()])
ins = insert(datetime_test_table).values({'dt_col_name': datetime.datetime.now()})
ins = insert(datetime_test_table).values(dt_col_name=datetime.datetime.now())

Related


SQLAlchemy "AttributeError: 'str' object has no attribute 'c'"

WiGeeky: I have two tables named usersand permissionsI want to create a relationship between them using the specified table userPermissions. Here's what my code looks like: 类User(Base): __tablename__ ='用户' id =列(Integer,primary_key = True) first_

AttributeError 'SQLAlchemy' object has no attribute 'create'

Sachin Mena I am trying to create a database using sqlalchemy and I am getting db.create.all()this error: File "<stdin>", line 1, in <module> AttributeError: 'SQLAlchemy' object has no attribute 'create' my code: from flask import Flask, render_template from

AttributeError 'SQLAlchemy' object has no attribute 'create'

Sachin Mena I am trying to create a database using sqlalchemy and I am getting db.create.all()this error: File "<stdin>", line 1, in <module> AttributeError: 'SQLAlchemy' object has no attribute 'create' my code: from flask import Flask, render_template from

AttributeError: 'SQLAlchemy' object has no attribute 'FieldType'

OK Python, flask and sqlalchemy newbies here. I am writing a small application to collect data (from an excel file) from different groups (departments). Each department will have associated tables and associated fields. Fields will have predefined types (numbe

AttributeError 'SQLAlchemy' object has no attribute 'create'

Sachin Mena I am trying to create a database using sqlalchemy and I am getting db.create.all()this error: File "<stdin>", line 1, in <module> AttributeError: 'SQLAlchemy' object has no attribute 'create' my code: from flask import Flask, render_template from

SQLAlchemy: AttributeError: 'table' object has no attribute 'id'

Yevgeny I am building a database that matches my local product catalog with foreign product catalogs. 'Catalog'SQLAlchemy works fine when I have only unique tables . After adding the tables Competitors, Competitors_catalogall attempts to add records to the two

AttributeError: 'SQLAlchemy' object has no attribute 'datetime'

Wayne I'm following a youtube tutorial on using Flask and when I run this code with python -m flask runit it shows this AttributeError: 'SQLAlchemy' object has no attribute 'datetime'. How can I fix this? from flask import Flask, render_template, url_for from

SQLAlchemy "AttributeError: 'str' object has no attribute 'c'"

WiGeeky: I have two tables named usersand permissionsI want to create a relationship between them using the specified table userPermissions. Here's what my code looks like: 类User(Base): __tablename__ ='用户' id =列(Integer,primary_key = True) first_

AttributeError: 'SQLAlchemy' object has no attribute 'FieldType'

OK Python, flask and sqlalchemy newbies here. I am writing a small application to collect data (from an excel file) from different groups (departments). Each department will have associated tables and associated fields. Fields will have predefined types (numbe

AttributeError 'SQLAlchemy' object has no attribute 'create'

Sachin Mena I am trying to create a database using sqlalchemy and I am getting db.create.all()this error: File "<stdin>", line 1, in <module> AttributeError: 'SQLAlchemy' object has no attribute 'create' my code: from flask import Flask, render_template from

AttributeError 'SQLAlchemy' object has no attribute 'create'

Sachin Mena I am trying to create a database using sqlalchemy and I am getting db.create.all()this error: File "<stdin>", line 1, in <module> AttributeError: 'SQLAlchemy' object has no attribute 'create' my code: from flask import Flask, render_template from

SQLAlchemy: AttributeError: 'table' object has no attribute 'id'

Yevgeny I am building a database that matches my local product catalog with foreign product catalogs. 'Catalog'SQLAlchemy works fine when I have only unique tables . After adding the tables Competitors, Competitors_catalogall attempts to add records to the two

SQLAlchemy: AttributeError: 'table' object has no attribute 'id'

Yevgeny I am building a database that matches my local product catalog with foreign product catalogs. 'Catalog'SQLAlchemy works fine when I have only unique tables . After adding the tables Competitors, Competitors_catalogall attempts to add records to the two

SQLAlchemy: AttributeError: 'table' object has no attribute 'id'

Yevgeny I am building a database that matches my local product catalog with foreign product catalogs. 'Catalog'SQLAlchemy works fine when I have only unique tables . After adding the tables Competitors, Competitors_catalogall attempts to add records to the two

SQLAlchemy: AttributeError: 'table' object has no attribute 'id'

Yevgeny I am building a database that matches my local product catalog with foreign product catalogs. 'Catalog'SQLAlchemy works fine when I have only unique tables . After adding the tables Competitors, Competitors_catalogall attempts to add records to the two

AttributeError: 'settings' object has no attribute 'items'

MTMA: I'm very new to python and have been trying to teach myself (it's not the best way to do python, but I need it too for time reasons). The modules I imported are Tkinter and csv. Let me know if you have any questions, For brevity, I won't post the entire

Python - AttributeError: 'str' object has no attribute 'items'

Bjarne stroustoup I am a beginner Tkinter. I am trying to make a phonebook GUI application. So, I'm just getting started, here is my source code: #This is my python 'source.py' for learning purpose from tkinter import Tk from tkinter import Button from tkinte

AttributeError: 'list' object has no attribute 'items' in scrape

shenzhou I was doing a husky with python3.5 and it happened: Traceback (most recent call last): File "F:/PyCharm/xiaozhou/main.py", line 6, in <module> cmdline.execute("scrapy crawl nvospider".split()) File "F:\Python3.5\lib\site-packages\scrapy\cmdline.

Flask - AttributeError: 'module' object has no attribute 'items'

Utopia I am using flask-restful and have the following API class: views.py from datetime import date from flask import jsonify from flask.ext.restful import Resource, reqparse from backend import db from .models import User, Post, Comment, WorkExperience from

AttributeError: 'settings' object has no attribute 'items'

MTMA: I'm very new to python and have been trying to teach myself (it's not the best way to do python, but I need it too for time reasons). The modules I imported are Tkinter and csv. Let me know if you have any questions, For brevity, I won't post the entire

Flask - AttributeError: 'module' object has no attribute 'items'

Utopia I am using flask-restful and have the following API class: views.py from datetime import date from flask import jsonify from flask.ext.restful import Resource, reqparse from backend import db from .models import User, Post, Comment, WorkExperience from

Python - AttributeError: 'str' object has no attribute 'items'

Bjarne stroustoup I am a beginner Tkinter. I am trying to make a phonebook GUI application. So, I'm just getting started, here is my source code: #This is my python 'source.py' for learning purpose from tkinter import Tk from tkinter import Button from tkinte