简体   繁体   English

尝试格式化返回的_set

[英]Trying to format returned _set

I am trying to populate my form with a list of plans. 我正在尝试用计划列表填充表单。

Here is my unicode for the Plans model 这是我对Planning模型的unicode

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: 现在,我将调用get_owners,如下所示:

def 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. 您只是从get_owners返回原始的get_owners ,Python对此调用了repr()将其插入到字符串中。

The best bet is to do the formatting within get_owners : 最好的选择是在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. 您的get_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: 或者,在其他python代码中,您可以根据需要将其组成一个字符串:

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.) (除了__unicode__这样的明显例外,该例外专门关于如何将模型显示为unicode文本。)

It looks like you need to add a __unicode__ method to PlanMember as you did for Plan . 它看起来像你需要添加__unicode__方法PlanMember像你一样的Plan

def __unicode__(self):
    label = "Name: %s, [%s]" % (self.name, self.membership_type)
    return unicode(label)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM