Almaz
Almaz

Reputation: 301

values_list() in query_set is showing only numbers but not the names of countries

I selected my field with 'values_list' which contains name of countries. But what I get is country_id numbers.

I already used flat=True but it did not help any.

my models.py:

class Report(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    church_name = models.CharField(max_length=255)
    area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True)
    water_baptism = models.IntegerField(default=0)
    holy_ghost = models.IntegerField(default=0)

    def __str__(self):
        return '%s' % self.area

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

my views.py:

def report_cities(request, pk):
    countries = Report.objects.values_list('country', flat=True)

    context = {
        'countries':countries
    }
    return render(request, 'users/report_countries.html', context)

my html

  <h1>Report Countries</h1>

  {% for country in countries %}
  {{country}}
  {% endfor %}


Upvotes: 1

Views: 53

Answers (1)

Jamie J
Jamie J

Reputation: 1305

Use Report.objects.values_list('country__name', flat=True) (assuming that is the country name field on the country model). By default django will list the object id if no field is specified.

E.G if your country model was

class Country(models.Model):
    name = Charfield()
    another_field = ...

The above query would now return a list of the names.

Upvotes: 3

Related Questions