我有3个依赖下拉列表的乡村城市之路。
从数据库中预先填充国家/地区,然后根据第一个国家/地区的选择显示相关城市。
问题在于,一旦用户从第一个下拉列表中进行选择,系统就会显示以下错误:
all_cities = selected_country.City_set.all()AttributeError: “国家”对象没有属性“城市集”
我不知道如何解决此错误。
class Country(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return str(self.name)
class City(models.Model):
name = models.CharField(max_length=100)
country = models.ForeignKey(Country,on_delete=models.CASCADE)
def __str__(self):
# return'id : {0} MouhafazatID :{1} Name :{2}'.format(self.id,self.MouhafazatID,self.name)
return str(self.name)
class Road(models.Model):
Vil = models.CharField(max_length=100)
city= models.ForeignKey(City,on_delete = models.SET_NULL, null=True)
country= models.ForeignKey(Country,on_delete = models.SET_NULL,null=True)
def __str__(self):
return str(self.Vil)
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('select#selectcountries').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var country_name = optionSelected.text();
data = {'cnt' : country_name };
alert(country_name);
$.ajax({
type:"GET",
url:'/getdetails',
// data:JSON.stringify(data),
data:data,
success:function(result){
console.log(result);
$("#selectcities option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>'+ result[i].name +'</option>');
};
},
});
});
});
</script>
</head>
<body>
<select name="selectcountries" id="selectcountries">
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="selectcities" id="selectcities">
</select>
<select name ="selectroads" id="selectroads">
</select>
</body>
</html>
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from testapp.models import *
import json as simplejson
def home2(request):
countries = Country.objects.all()
print("countries =", countries)
return render(request, 'home2.html',{'countries': countries})
def getdetails(request):
if request.method == 'GET' and request.is_ajax():
country_name = request.GET.get('cnt', None)
print ("ajax country_name ", country_name)
result_set = []
all_cities = []
answer = str(country_name[1:-1])
print('answer = ' ,answer)
selected_country = Country.objects.get(name=answer)
print ("selected country name ", selected_country)
all_cities = selected_country.City_set.all()
print("cities are: " , all_cities)
for city in all_cities:
print ("city name", city.name)
result_set.append({'name': city.name})
return HttpResponse(simplejson.dumps(result_set),content_type='application/json')
# return JsonResponse(result_set,status = 200)
else:
return redirect('/')
如您所见,我正在以json格式传递数据。
,但 views.py 中的函数会执行到这一行
print ("selected country name ", selected_country)
具有正确的值。
,然后显示错误。
答案 0 :(得分:1)
使用小写字母时,您需要将City_set
替换为city_set
。
答案 1 :(得分:1)
访问反向外键关系时,在提及相关模型时始终使用小写字母。是
all_cities = selected_country.city_set.all()
为提高可读性,在声明外键字段时,请使用related_name
属性。示例:
class City(models.Model):
name = models.CharField(max_length=100)
country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='cities')
通过添加上面的related_name
属性,您可以按以下方式访问城市:
all_cities = selected_country.cities.all()