开发者

Output MySQL query results in Django shell

I have the following Django Model which retrieves 3 records from a database. The class below represents a Model within a Django application I'm building. I realize that the parameters taken in by the create_hotspots function are not being used. I just simplified what the code looked like previously for the purposes of explaining my problem.

from django.db import models
from django.db import connection, transaction
import math
import MySQLdb

class Victims(models.Model):

    def __init__(self):
        self.results=[]
    def create_hotspots(self,radius,latitude,longitude):

        self.radius=str(radius)
        self.latitude=str(latitude)
        self.longitude=str(longitude)

        db=MySQLdb.connect (host = "localhost", user = "root",passwd = "pass",db = "test")
        cursor = db.cursor ()
        cursor.execute("""SELECT * FROM poi_table""")
        self.results=cursor.fetchall()
        cursor.close ()
        db.close ()
    def __unicode__(self):
        return self.results

Now, assume that I open the Django shell and I execute the following instructions:

>>from PyLayar.layer.models import Victims
C:\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWarning: the sets module is deprecated
  from sets import Immut开发者_如何学JAVAableSet
>>> v=Victims()
>>> v.create_hotspots(1000, 42.3931955679, -72.5289916992)
>>> Victims.objects.all()
[]

My question is why does the Victims.objects.all() instruction return no results. The SQL query returns 3 results, and the results variable stores the resulting tuple.


The Victims.create_hotspots method has no return statement. What did you expect it to return?

Also, Victims.create_hotspots does not do a save() to save the Victims instance.

BTW, the use of raw SQL inside a models object is often a really poor idea. You should consider making your "poi_table" a proper part of the Django model and using proper relational database design to avoid querying one class while trying to create an instance of another.

If you are trying to create "persistent aggregate" objects, you should consider doing something different.

v= Victim.objects.create( radius, lat, lon, Poi.objects.all())
v.save()

This will disentangle your two models allowing you to write simpler, less heavily-entangled models using simple Django processing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜