如何从JSON中的模板重写数据?

时间:2019-05-07 13:32:04

标签: django django-models django-templates django-views

我有这个模型:

class Category(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.CharField(max_length=250)

    def get_absolute_url(self):
        return reverse('categories_url', args=[str(self.id)])

class Company(models.Model):
    name = models.CharField(max_length=150, unique=True)
    country = models.CharField(max_length=50)

class Motobike(models.Model):
    name = models.CharField(max_length=150)
    company = models.ForeignKey('Company', on_delete=models.CASCADE)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)

在我看来。.

class CategoryView(DetailView):
    model = Category
    template_name = 'bikes_site/categories_detail.html'
    pk_url_kwarg = 'pk'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        category = self.get_object()
        context['motobikes'] =  Motobike.objects.filter(category_id=category.pk)
        return context

并在模板中显示所有内容

{% for motobike in motobikes %}
    <ul>
        <p> Name:        {{ motobike.name }}</p>
        <p> Company:     {{ company.name }}</p>
        <p> Category:    {{ object.name }}</p>
        <p> Description: {{ object.description }} </p>
    </ul>
{% endfor %}

如何重写它以JSON格式显示(此类任务)?必须通过HttpResponse。

这是我的考试:

client = Client()

    category_id = Category.objects.get(name='Мотоциклы').id

    response = client.get(f'/categories/{category_id}/')

    assert response.status_code == 200

    response_data = json.loads(response.content.decode('utf-8'))

    assert len(response_data) == 2

    assert response_data[1]['name'] == 'Ninja Turbo'

    assert response_data[1]['vendor'] == 'Kawasaki'

    assert response_data[1]['category'] == 'Мотоциклы'

    assert response_data[1]['description'] == ''

还有什么可以推公司的名字?

0 个答案:

没有答案