Django QuerySet 不返回任何内容 [英] Django QuerySet returns nothing
本文介绍了Django QuerySet 不返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个国家/地区列表,例如,它们都有自己的网址 www.example.com/al/.每个国家都有一个城市列表,但 object_list 是空的
I have a list of countries, they all have there own url www.example.com/al/ for example. There is a list of cities for every country but the object_list is empty
我的观点:
class CityOverview(generic.ListView):
template_name = 'shisha/pages/country_index.html'
model = City
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country__name=country_id)
我的模型:
class Country(models.Model):
COUNTRY_CHOICES = (
('al', 'Albania'),
('ad', 'Andorra'),
#etc. etc.
)
name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='nl')
def __str__(self):
return self.name
class City(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
def __str__(self):
return self.name
我的网址:
path('<str:country_id>', views.CityOverview.as_view(), name='country'),
我的模板:
{{ object_list }}
它返回一个空的查询集
<QuerySet []>
有人知道是什么问题吗?
Does anyone know what the problem is?
推荐答案
可能是你返回的查询有误,
May be your returning query is wrong,
class Country(Models.model):
country_id=Autofield()
country_name=CharaField()
在 Views.py 中
in Views.py
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country_id=country_id)
这篇关于Django QuerySet 不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文