我有 2 个模型,城市和国家。我想根据所选国家/地区在页面上显示该国家/地区的城市。我尝试查询将国家/地区模型传递给城市模型以查找与该国家/地区相关的所有城市,但目前,页面显示所有城市,无论该国家/地区是什么。
当用户从页面中选择国家/地区时,如何显示该国家/地区的城市?
非常感谢任何帮助或建议。
models.py
class City(models.Model):
country = models.ForeignKey('Country', on_delete=models.CASCADE, related_name='country')
name = models.CharField(max_length=90, verbose_name='City name')
slug = models.SlugField(null=True, unique=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('city:cities', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
return super().save(*args, **kwargs)
class Country(models.Model):
country_name = models.CharField(max_length=50, verbose_name='Country name',unique=True)
slug = models.SlugField(null=True, unique=True)
def __str__(self):
return self.country_name
def get_absolute_url(self):
return reverse('city:cities', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.country_name)
return super().save(*args, **kwargs)
views.py
class CountriesListView(ListView):
template_name = "countries.html"
model = Country
context_object_name = "countries"
class CitiesListView(ListView):
template_name = "cities_list.html"
model = City
context_object_name = "cities"
def get_context_data(self, *args, **kwargs):
context = super(CitiesListView, self).get_context_data(*args,**kwargs)
countries = Country.objects.all()
cities = City.objects.filter(country__in=countries)
context['cities'] = cities
return context
模板
# countries.html
<h1>Countries</h1>
{% for country in countries %}
<h3><a href="{% url 'city:cities' country.slug %}">{{ country.country_name }}</h3>
{% endfor %}
# cities_list.html
<h1>Cities</h1>
{% for city in cities %}
<div>
<h3><a href="{% url 'city:details' city.slug %}">{{ city }}</a></h3>
</div>
{% endfor %}
最佳答案
related_name=…
parameter [Django-doc]是反向关系的名称,因此可以访问特定Country
的City
对象。因此将其命名为 Country
并不是一个好主意。您可以将其重命名为cities
,例如:
class City(models.Model):
country = models.ForeignKey(
'Country',
on_delete=models.CASCADE,
<b>related_name='cities'</b>
)
# …
您可以使用 DetailView
呈现单个 Country
,因此:
from django.views.generic.detail import <b>DetailView</b>
class CountryDetailView(<b>DetailView</b>):
template_name = 'country_detail.html'
model = Country
context_object_name = 'country'
在 URL 中,您可以使用 slug 字段以名称 cities
注册此 View :
# app/urls.py
from django.urls import path
from . import views
app_name='city'
urlpatterns = [
# …,
path(
<b>'country/<slug:slug>'</b>,
views.CountryDetailView.as_view(),
<b>name='cities'</b>
),
]
在模板中,您可以反向访问关系:
<!-- country_detail.html -->
{{ country }}
{% for <b>city in country.cities.all</b> %}
{{ city }}
{% endfor %}
关于python - 如何从数据库中获取一个国家的城市列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63661746/