python - Django count number of times each ForeignKeyField value appears in table & retain __unicode__() -
django 1.3, python 2.7
i have following models (some irrelevant fields omitted):
class encounter(models.model): uuid = models.slugfield(max_length=36, unique=true, default=make_uuid, editable=false) created = models.datetimefield(auto_now_add=true) subject = models.foreignkey('subject', to_field='uuid') class subject(models.model): given_name = models.charfield(max_length=64) family_name = models.charfield(max_length=64) system_id = models.charfield(max_length=32, blank=true) uuid = models.slugfield(max_length=36, unique=true, default=make_uuid, editable=false) def __unicode__(self): return u'%s, %s - %s' % (self.family_name, self.given_name, self.system_id)
i know subjects appear in encounters table , how many times appear. following code want 1 exception:
s_in_e = encounter.objects.values('subject').annotate(mycount=count('subject'))
when attempt display results of annotation follows:
{% thing in s_in_e %} <p>{{ thing.subject }} visited {{ thing.mycount }} time{{ thing.mycount|pluralize }}.</p> {% endfor %}
it displays subject's uuid
instead of __unicode__()
. research has shown property of values()
operating on foreignkeyfield
- returns id, not object. there way calculate number of times each subject appears in encounters table can @ least display __unicode__()
value? ideally have access entire subject object.
i working on else's code, cannot edit existing structure of models. might able add new field model if necessary.
you can start subject
, use following code:
subjects = subject.objects.prefetch_related('encounter_set')
and in template:
{% subject in subjects %} <p> {{ subject }} visited {{ subject.encounter_set.count }} time{{ subject.encounter_set.count|pluralize }}.</p> {% endfor %}
prefetch_related
related encounters in single additional query. subject.encounter_set
queryset
, can use count()
method on other queryset.
Comments
Post a Comment