我有一个国家/地区列表,例如,它们都有自己的网址www.example.com/al/。每个国家都有一个城市列表,但object_list为空
我的观点:
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
<QuerySet []>
有人知道是什么问题吗?
答案 0 :(得分:0)
可能是您返回的查询有误,
class Country(Models.model):
country_id=Autofield()
country_name=CharaField()
在Views.py
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country_id=country_id)
答案 1 :(得分:0)
问题是您正在尝试将country__name
与country_id
匹配。将get_queryset
中的最后一行更改为return City.objects.filter(country__id=country_id)
,现在将根据country_id
的国家/地区ID过滤提供的City
。