Reputation: 9763
I am trying to query a MySQL database using Django. I pieced this code together using several sources. Can someone explain what is wrong with how I am passing the query? I would appreciate suggestions or links about how to improve my code as well since I'm new to Python and Django. The error I get is:
TypeError: query() takes exactly 1 argument (2 given)
My class: (does database connection and displays result in a view)
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'))
Upvotes: 0
Views: 164
Reputation: 952
Your instance method should always take in self as the first parameter like this:
def query(self, q):
myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database )
...
self
will point to the instance of the class you created.
Upvotes: 1