Monday, January 31, 2011

Selecting related objects with condition

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