Saturday, August 31, 2013

Implementing Raw SQL in Models problem

### PART A

Hello, in Python shell I run a Raw SQL and get a One-to-Many list output.

$ python manage.py shell
Python 2.7.3 (default, Apr 10 2013, 05:13:16) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 
>>> 
>>> from navi_polls.models import Word, Altword
>>> from django.db import connection
>>> 
>>> cursor = connection.cursor()
>>> 
>>> for row in cursor.execute('SELECT navi_polls_word.rosword, navi_polls_altword.alt_ros_word, navi_polls_altword.votes FROM navi_polls_altword INNER JOIN navi_polls_word ON (navi_polls_altword.rosword_id=navi_polls_word.id)'):
...     print row
... 
(u'Paper', u'Leaf', 300)
(u'Paper', u'Leafy', 0)
(u'Page', u'Leafy 2', 18)
(u'Page', u'Leafy 3', 50)
>>> 
____________________________________________________________________________________________
### PART B

I don't really understand how to implement this Raw SQL into my Models file so that it returns the above same
list when I type this in Python shell:

>>> Altword.objects.vote_order()
____________________________________________________________________________________________
### PART C

class AltwordManager(models.Manager):
    def vote_order(self):
        "Returns a 1:M list ordered by votes."
        cursor =  connection.cursor()
        cursor.execute("""
SELECT navi_polls_word.rosword, navi_polls_altword.alt_ros_word, navi_polls_altword.votes
FROM navi_polls_altword INNER JOIN navi_polls_word
ON (navi_polls_altword.rosword_id=navi_polls_word.id)
        """)
        return for row in cursor.fetchall()


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment