显示对象及其外键对象

时间:2018-04-25 14:52:44

标签: django python-3.x django-models django-templates django-views

需要一些显示数据的帮助。

models.py

class Brand(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Car(models.Model):
    name = models.CharField(max_length=100)
    brand = models.ForeignKey(Brand, related_name='brands', on_delete=models.CASCADE)

    def __str__(self):
        return self.brand.name + " - " + self.name

views.py

def car_view(request):

    # pls halp

如何显示品牌列表以及每个品牌后的汽车列表?示例如下所示。

<html>
    <ul>
    <li>Toyota</li>
    <ul>
        <li>Corolla</li>
        <li>Avensis</li>
        <li>Yaris</li>
    </ul>
    <li>Volkswagen</li>
    <ul>
        <li>Golf</li>
        <li>Transporter</li>
        <li>Passat</li>
    </ul>
    </ul>
</html>

1 个答案:

答案 0 :(得分:2)

首先纠正模型related_name,

class Brand(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Car(models.Model):
    name = models.CharField(max_length=100)
    brand = models.ForeignKey(Brand, related_name='cars', on_delete=models.CASCADE)

    def __str__(self):
        return self.brand.name + " - " + self.name

您可以访问Brand模型实例中的所有汽车brand.cars.all()

def car_view(request):  
    return render("list.html", {'brand_list': Brand.objects.all()})

模板类似于

<!-- list.html -->
{% block content %}
     {% for brand in brand_list %}
          {{ brand.name }}
          {% for car in brand.cars.all %}
              {{car.name}}
          {% endfor %}
     {% endfor %}
{% endblock %}