query_set中的values_list()仅显示数字,但不显示国家/地区名称

时间:2019-04-25 12:42:33

标签: python django

我使用“ values_list”选择了包含国家名称的字段。但是我得到的是country_id数字。

我已经使用了flat = True,但是它没有任何帮助。

我的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')

我的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)

我的html

  <h1>Report Countries</h1>

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


1 个答案:

答案 0 :(得分:3)

使用let str = "Plain text <p>First para content</p> Another plain text<p>Second para content</p> Another random text and other stuff <p>Third Para content</p>" var result = str.match(/<p>(.*?)<\/p>/g).map(val => { return val.replace(/<\/?p>/g, '') }) console.log(result)(假设这是国家/地区模型上的国家/地区名称字段)。默认情况下,如果未指定任何字段,则django将列出对象ID。

例如,如果您的国家/地区型号为

Report.objects.values_list('country__name', flat=True)

上面的查询现在将返回名称列表。