如何使用django框架中的sqlalchemy在mysql数据库中插入数据?

时间:2017-02-12 18:14:16

标签: python mysql django orm sqlalchemy

我是django框架中的新手,我正在尝试为“register”创建一个api,我希望在执行后将数据插入到db中但无法执行此操作。

我正在尝试创建auth_user的对象并尝试session.add(auth_user_object) 但它没有给出任何错误,甚至没有向mysql db添加数据。

我可以从db获取(获取)数据。

创建所有表格。

然后我正在做inspect db并获取db表类并根据sqlalchemy修改它。

但是我无法使用sqlalchemy将数据添加到db表。

请帮帮我。 这样做的最佳方法是什么。

my models.py

from __future__ import unicode_literals

from django.db import models

from sqlalchemy import *
from sqlalchemy import types
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import *


# Create your models here.
Base = declarative_base()
class Designation(Base):
    __tablename__='designation'
    id = Column(autoincrement=True,primary_key=True) 
    designation_name = Column(String) 
    designation_desc = Column(String) 


class UAuthUser(Base):
    __tablename__='auth_user'
    id = Column(autoincrement=True,primary_key=True)
    password = Column(String)
    last_login = Column(DateTime)
    is_superuser = Column(Integer)
    username = Column(String)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String)
    is_staff = Column(Integer)
    is_active = Column(Integer)
    date_joined = Column(DateTime)
    fcm_token = Column(String)
    designation_id = Column(Integer)
    ForeignKeyConstraint(['designation'], ['designation.id']

my views.py

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.shortcuts import render
from designation.models import *
#from designation.serializers import *
from sqlalchemy.orm import *
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
import sqlalchemy, sqlalchemy.orm
import urllib
import urllib2
import json
from datetime import datetime
import collections
import requests
from sqlalchemy import create_engine
import MySQLdb
import mysql.connector

def mysqlconnection(db):
    dialect = 'mysql'

    username = 'root'
    password = ''
    server = 'localhost'
    port = '3306'
    database = db
    url=dialect+'://'+username+':'+password+'@'+server+':'+port+'/'+database
    try:
        engine = create_engine(url)
        Session = sqlalchemy.orm.sessionmaker(bind=engine)
        session = Session()
        return session
    except:
        return ("Could not establish connection")

# def mysqlCursor(db):
#   cnx = mysql.connector.connect(database='db')
#   cursor = cnx.cursor(raw=True, buffered=True)

@api_view(['GET', 'POST'])
def designation(request):
    session = mysqlconnection('hrdb')
    #query = session.query(Designation.id,Designation.designation_name,Designation.designation_desc).all()
    new_designation=Designation(id=3,designation_name='uday',designation_desc='shankar')
    session.add(new_designation)
    session.bulk_save_objects(new_designation)
    #session.commit()
    session.close()
    return Response('query')


@api_view(['GET', 'POST'])
def register(request):
    session = mysqlconnection('hrdb')
    password1 = "jhg$"
    last_login1 = "2017-02-08 16:12:52.822000"
    is_superuser1 = 0
    username1 = "bibek_n"
    first_name1 = "bibek"
    last_name1 = "neupane"
    email1 = "vivek@gmail.com"
    is_staff1 = 0
    is_active1 = 1
    date_joined1 = "2017-02-08 16:12:52.822000"
    fcm_token1 = "abc"
    designation_id1 = 1
    new_user = UAuthUser(password = password1,last_login = last_login1,is_superuser= is_superuser1,username = username1,first_name = first_name1,last_name = last_name1,email = email1,\
        is_staff = is_staff1,is_active = is_active1,date_joined= date_joined1,fcm_token = fcm_token1,designation_id = designation_id1)
    session.add(new_user)
    #query = session.query(AuthUser).insert()
    #session.commit()
    session.close()
    return Response('query')

2 个答案:

答案 0 :(得分:1)

您不需要在Django中使用SQL alchemy。 Django提供ORM来进行数据库查询。你也可以像这样定义模型。

class UAuthUser(models.Model):
    __tablename__='auth_user'
    password = models.CharField(max_length=20)
    last_login = models.DateField()

参考此链接。 https://docs.djangoproject.com/en/1.10/topics/db/models/ https://docs.djangoproject.com/en/1.10/topics/db/queries/

答案 1 :(得分:0)

错误地我没有向Id提供数据类型,这就是为什么错误即将发生。