Monday, January 31, 2011

Selecting related objects with condition


I have a model:

class Work(models.Model):
user = models.ForeignKey(
closed = models.DateTimeField(


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

context['users'] = User.objects.all()


{% 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 :)


You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment