I
I
Igor Malyshev2015-11-29 00:41:18
Django
Igor Malyshev, 2015-11-29 00:41:18

How to implement filtering?

In the simple example below, in the "city_list.html" file, you need to display cities for their countries. If anyone knows how to do this, please help!
models.py

class Country(models.Model):
  name = models.CharField(max_length=50)
  country_slug = models.SlugField(max_length=50, unique=True)

  def __str__(self):
    return self.name

  def get_absolute_url(self):
    return reverse('country', kwargs={'country_slug': self.country_slug})

class City(models.Model):
  city_country = models.ForeignKey(Country)
  name = models.CharField(max_length=50)
  city_slug = models.SlugField(max_length=50, unique=True)

  def __str__(self):
    return self.name

urls.py
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'example.views.home'),
    url(r'^(?P<country_slug>[-\w]+)$', CityListView.as_view(), name='country'),
]

views.py
def home(request):
  return render_to_response("home.html", {'countries': Country.objects.all()})


class CityListView(ListView):
  model = City
  context_object_name = "cities"
  template_name = "city_list.html"

home.html
{% for country in countries %}
<li><a href="{{ country.get_absolute_url }}">{{ country.name }}</a></li>
  {% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2015-11-29
@Domuk

class CityListView(ListView):
    model = City
    context_object_name = "cities"
    template_name = "city_list.html"

    def get_queryset(self, *args, **kwargs):
        qs = super(CityListView, self).get_queryset(*args, **kwargs)

        country = Country.objects.get(country_slug=self.kwargs.get('country_slug'))
        return qs.filter(city_country=country)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question