Monday, January 31, 2011

Re: Selecting related objects with condition

The easiest way would be to get a list of all closed work items, ordered
by user:

context['work'] = Work.objects.filter(whatever).order_by('user')

{% for work_item in work %}
{% ifchanged %}Display {{work_item.user}}{% endifchanged %}
Display {{ work_item }}
{% endfor %}

--
Michael <mhall119@gmail.com>

On Mon, 2011-01-31 at 18:45 +0100, Martin Tiršel wrote:
> Hello,
>
> I have a model:
>
> class Work(models.Model):
> ...
> user = models.ForeignKey(
> User
> )
> closed = models.DateTimeField(
> blank=True
> )
>
> ...
>
> Now, I want to print all users and for each user all Works closed between
> a specific date. If I don't need the "closed between" condition, I would
> do:
>
> view.py:
>
> ...
> context['users'] = User.objects.all()
> ...
>
> template.html:
>
> {% for user in users %}
> {% for work in user.work_set.all %}
> ...
> {% endfor%}
> {% endfor %}
>
> But what I have to do, if I need condition to select specific work
> records? I have only one idea how to do this - load all users, iterate
> through each user and extract his works and make a list of dictionaries
> with {'user':..., 'works':...} items. But I have a feeling that this is
> not the "right" way and Django has something to solve this kind of
> problems too :)
>
> Thanks,
> Martin
>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment