I am trying to populate my form with a list of plans.
Here is my unicode for the Plans model
def __unicode__(self):
label = "ID: %s, Member(s): %s, Plan Type: %s" % (self.id, self.get_owners(), self.plan_type)
return unicode(label)
Now I call get_owners which is shown below:
de开发者_开发百科f get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"])
return owners
But my output shows:
[<PlanMember: Name, [membership_type]><PlanMember: Name, etc etc>]
How do I go about displaying the output without the brackets, and more along the lines of:
Name [membership_type], Name [membership_type], etc
You're just returning the raw queryset from get_owners
, and Python is calling repr()
on that to insert it into the string.
The best bet is to do the formatting within get_owners
:
def get_owners(self):
owners = ...
return u", ".join(unicode(o) for o in owners)
Your get_owners
method is doing exactly what it should do: return a set of owners. In your template you can then loop over these owners and display them however you like:
{% for owner in plan.get_owners %}
{{ owner }}
{% endfor %}
Or, inside other python code, you can compose it into a string as you like:
def __unicode__(self):
owners = u', '.join(self.get_owners())
label = "ID: %s, Member(s): %s, Plan Type: %s" % (self.id, owners, self.plan_type)
return unicode(label)
Model methods shouldn't enforce display; they should only return data. (Except for obvious exceptions like __unicode__
which is specifically about how to display the model as unicode text.)
It looks like you need to add a __unicode__
method to PlanMember
as you did for Plan
.
def __unicode__(self):
label = "Name: %s, [%s]" % (self.name, self.membership_type)
return unicode(label)
精彩评论