0

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'))
3
  • 1
    Don't do any of this. You're using Django; at least use the built-in connection object to run your SQL, but much better use the model layer and don't use SQL at all. Commented Sep 22, 2017 at 18:14
  • Im new to django, what do you mean by the built-in connection object? Could you provide an example or give me an idea of what to google? Commented Sep 22, 2017 at 18:37
  • Look, how to use Django models and queries is covered in the tutorial and elsewhere in the docs. You should read and follow that, rather than "piecing it together" from random sources. Commented Sep 22, 2017 at 18:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.