七度&光 2013-09-17 19:35 采纳率: 22.2%
浏览 48

Django查询不匹配

I have the following Django Model:

class State(models.Model):
    name = models.CharField(max_length=80,null=False)
    latitude = models.CharField(max_length=80,null=False)
    longitude = models.CharField(max_length=80,null=False)

def __unicode__(self):
    return self.name

In my views.py file I've created the following method:

def getCoords(request):
    if request.is_ajax():
        if request.method == 'POST':
            try:
                state = request.POST['state'] #receives the state from JS
                stateInstance = State.objects.get(name=state)
                stateLat = stateInstance.latitude
                stateLong = stateInstance.longitude
                data = {"lat" : stateLat, "long" : stateLong}
             except State.DoesNotExist:
                 return HttpResponse("No record")

             return HttpResponse(simplejson.dumps(data)) #returns json 

So I'm sending this method a param through ajax, let's say "California". The state variable gets the value (I have proved that) but the query doesn't get executed, it returns the query doesn't match message. I've tried with the following as well:

    state = request.POST['state']
        if state == 'California':
            return HttpResponse("Yes!")
        else:
            return HttpResponse(state)

When this snippet returns the state it displays California which means state's value is correct but the query is not executed properly. I don't know what's going on. Any thoughts?

  • 写回答

1条回答 默认 最新

  • weixin_33694620 2013-09-17 20:21
    关注

    Make sure you're connecting to the correct database in your settings.py. Make sure the record actually does exist with plain old SQL.

    SELECT * FROM [app_name]_state WHERE name = 'California';
    

    Also, try it from the Django shell. python manage.py shell

    >>> from [app_name].models import State
    >>> s = State.objects.get(name='California')
    >>> s
    <State: California>
    

    Make sure that what is actually being sent is sent as POST, and not accidentally a GET variable in the URL. Also, make sure that the post variable has no extra characters and that it is actually valid. A decent way to do that is to just print it to the console, or if AJAX, with Firebug.

    # Single quotes added so you can see any extra spaces in the console
    print "'%s'" % state 
    
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程