除了创建字典之外,还有更好的方法来获取和显示相关对象的数据吗?

时间:2017-09-04 16:42:18

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

我有两个模型,其中一个具有另一个外键:

型号:

class WhoAmI(models.Model):
    name = models.CharField(max_length=200)
    company = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class SolarClient(models.Model):
    name = models.CharField(max_length=200)
    client_owner = models.ForeignKey(WhoAmI, on_delete=models.CASCADE, related_name='solarclients')
    addr = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    state = models.CharField(max_length=200)
    email = models.EmailField()

我正在尝试简单地显示一个html表,显示销售人员拥有的每个客户,首先列出销售人员,并在其名称下面显示客户表。

我能弄清楚如何做到这一点的唯一方法是使用下面显示的代码创建一个字典。

class Homeowners(DetailView):
    def get(self, request, **kwargs):
        salespersons = WhoAmI.objects.all() 
        homeowners = SolarClient.objects.all().order_by("client_owner")  #the name 'objects' is the Manager

        rangers = {}
        for e in salespersons:
            k = salespersons.get(id = e.id)
            v = k.solarclients.all()
            rangers[k] = v


        return render(request, 'homeowners.html', {'homeowners': homeowners, 'salespersons': salespersons, 'rangers': rangers })

然后我使用:

遍历字典
{% for key, values in rangers.items %}
           ... display salesperson
            {% if values %}
               {% for v in values %}
                .... display clients
               {% endfor %}
            {% else %}
            ... display "No Clients"
        {% endif %}
{% endfor %}

有更有效的方法吗?将数据放入字典中显示它似乎很愚蠢,但经过许多小时尝试不同的方法后,这是我显示数据的唯一方法。

感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

views.py

class Homeowners(DetailView):
    def get(self, request, **kwargs):
        salespersons = WhoAmI.objects.all() 
        return render(request, 'homeowners.html', {'salespersons': salespersons })

HTML:

{% for sales in salespersons %}
 {% for client in sales.solarclients.all %}
   ------ Print Client
 {% empty %}
    ----  Client not exist
 {% endfor %}
{% endfor %}

答案 1 :(得分:0)

在Django中有一个名为regroup的非常方便的模板过滤器,可以完全满足您的需求。

# views.py
homeowners = SolarClient.objects.all().order_by("client_owner").select_related('client_owner')

return render(request, 'homeowners.html', {'homeowners': homeowners})

# homeowners.html
{% regroup homeowners by client_owner as home_owners_list %}

<ul>
{% for client_owner in home_owners_list %}
    <b>{{ client_owner.grouper }}</b>
    <ul>
        {% for client in client_owner.list %}
          <li>{{ client.name }}</li>
        {% endfor %}
    </ul>
{% endfor %}
</ul>

select_related方法仅用于提高性能,省略它不会影响功能。