Django MySQL数据库错误传递数据库查询

时间:2017-09-22 17:55:27

标签: python mysql django

我正在尝试使用Django查询MySQL数据库。我用几个来源拼凑了这段代码。有人可以解释我如何传递查询有什么问题吗?我很感激有关如何改进我的代码的建议或链接,因为我是Python和Django的新手。我得到的错误是:

TypeError: query() takes exactly 1 argument (2 given)

我的课程:(数据库连接并在视图中显示结果)

from helloservice.models import Snippet
from helloservice.serializers import SnippetSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from helloservice.serializers import UserSerializer
from rest_framework import permissions
from helloservice.permissions import IsOwnerOrReadOnly
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import renderers
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.decorators import detail_route

#sudo pip install MySQL-python
class DbConn():
    hostname = 'jdbc:mysql://xxxxxx.us-east-1.rds.amazonaws.com:3306'
    username = 'rrrr'
    password = 'xxxx'
    database = 'yyyy'

    def query(q):
        myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database )
        cur=conn.cursor()
        cur.execute(q)
        return cur

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    conn= DbConn()
    cur=conn.query('SELECT * FROM pulse.customer WHERE userId = 103')
    #return cur.objects.values_list('loginName')
    print(cur.objects.values_list('loginName'))

1 个答案:

答案 0 :(得分:1)

您的实例方法应始终将self作为第一个参数,如下所示:

def query(self, q):
    myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database )
    ...

self将指向您创建的类的实例。