Almaz
Almaz

Reputation: 301

How do I get list of cities of certain countries?

I am trying to show names of the cities of a certain countries {{city}}. For example if I click "USA" it should show the list of the cities in my database.
But I don't know how to filter it right.

I tried this but nothing show up.

Post.objects.filter(country='country').filter(city='city')

This is my model

class Post(models.Model):
    title = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    address = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)
    phone = models.CharField(max_length=255)
    website = models.CharField(max_length=255)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('users:blog')

This is my view


def cities(request):
    context = {
            'posts': Post.objects.filter(country='country').filter(city='city')
    }
    return render(request, 'users/cities.html', context)

This is my template:

{% for post in posts %}

<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
       <tbody>
        <tr>
          <td>{{ post.id }}</td>
          <td>{{ post.city }}</td>
        </tr>
    </tbody>
</table>


{% endfor %}

{% endblock %}

</div>

Upvotes: 0

Views: 470

Answers (1)

Ivan
Ivan

Reputation: 2675

You can use values_list and call distinct() to get city names from Post model:

views

def cities(request):
    queryset = Post.objects.filter(country='country').values_list(
        'city', flat=True).distinct().order_by('city')
    return render(request, 'users/cities.html', {'cities': queryset})

template

<table>
    <tbody>
    {% for city in cities %}
        <tr>
            <td>{{ city }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Upvotes: 1

Related Questions