问题
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
My View:
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)
My Model:
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
My Urls:
path('<str:country_id>', views.CityOverview.as_view(), name='country'),
My Template:
{{ object_list }}
It returns an empty QuerySet
<QuerySet []>
Does anyone know what the problem is?
回答1:
The problem is you are trying to match country__name
to country_id
. Alter the last line in get_queryset
to become return City.objects.filter(country__id=country_id)
which will now filter the country_id
supplied against City
's country id.
回答2:
May be your returning query is wrong,
class Country(Models.model):
country_id=Autofield()
country_name=CharaField()
in Views.py
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country_id=country_id)
来源:https://stackoverflow.com/questions/54865487/django-queryset-returns-nothing