开发者

Django "concat" query sets

So this one is a bit odd to describe, please bear with me :) Trying to explain without code won't make much sense so here's a brief example:

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

class Location(models.Model):
    address = models.CharField(max_length=200)
    employees = models.ForeignKey(Employee)   

class Company(models.Model):
    name = models.CharField(max_length=100)
    locations = models.ForeignKey(Location)

Let's say we want to print out every employee in a particular company via a template. Normally we would just do this:

{% for location in company.locations.all %}
    {% for employee in location.employees.all %}
        {{ employee.name }} <br/>
    {% endfor %}
{% endfor %}

Which works out great, but in this case I would like to print out a header at the top of the employee list if there are any employees, but leave off the header if no employees are present. In a typical loop I use forloop.first to indicate that the header should be shown, but in this case I can't. If I try it in the outer loop (locations) I may get a header when no employees are present, if I try it in the inner loop (employees) I'll only get the header for locations with employees, but I'll get one header per location instead of a single one for the entire list.

Now, my ideal solution to this would be to skip a step all together and have some way to iterate over all employees from the company level:

{% for employee in company.employees %}...{% endfor %}

Where employees开发者_StackOverflow社区 at the company level is essentially a concatenation of the employees query set for each location. I've looked into custom managers, but I'm not sure how to utilize them in this scenario.

Hopefully that makes some sense. Thanks for any suggestions!


You can just do the query (in the view) the other way round to get a single queryset of all employees of a company:

employees = Employee.objects.filter(location__company=company)

This has the added benefit of only requiring a single database hit, rather than one per location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜