Django: Sort query with common column value
Hey, Let's say I have this model:
class Log:
msg = CharField(...)
project = ForeignKey(..)
date = DateField(..)
Now let's say I want to select the 4 most recent logs:
logs = Log.objects.order_by('project').order_by('-date')[:4]
Further, I want to extract the logs that share the same 开发者_如何学运维project so in my template, I'd like to do something like:
{% for proj in projects %}
[Do something with the proj model instance]
{% for log in proj.logs(?) %}
[Do something with logs]
{% endfor %}
{% endfor %}
How to?
In your template you could regroup by project.
From the docs something (untested) like
{% regroup logs|dictsort:"project.id" by project as project_list %}
{% for project in project_list %}
{{ project.grouper }}
{% for item in project.list %}
[Do something with logs]
{% endfor %}
{% endfor %}
{% for proj in projects %}
{{ proj.name }}
{% for log in proj.log_set.all %}
{{ log.msg }}
{% endfor %}
{% endfor %}
If you use a related_name
for your ForeignKey (let's say "logs") you could you could use
proj.logs instead of proj.log_set. Check the docs.
If you need the latest logs for a project on a regular basis i'd consider writing a method for your Project model:
def recent_logs(self):
return self.log_set.all()[:4]
Then you could adjust the loop in your template to:
{% for log in proj.recent_logs %}
{{ log.msg }}
{% endfor %}
精彩评论