我是一名初级开发人员。在Django 1.8,Python 2.7.15中处理项目。
我想实现什么?
我想将组“ test_X”的名称更改为另一个字符串(付款标题),但不在数据库中...仅在表单的可见层中。 (SelectMultiple小部件)
在小组中,我有这样的东西:
Super Group
Extra Group
New Group
test_1
test_2
test_3
Great Group
test_4
(...)
“ test_x”组通过一对一字段连接到Payments模型。
只看我的代码:
class Payment(models.Model):
(...)
title = models.CharField(max_length=120, null=False)
group = models.ManyToManyField(Group)
virtual_group = models.OneToOneField(
Group,
null=True,
related_name='virtual_group',
)
class PaymentForm(forms.ModelForm):
class Meta:
model = Payment
fields = (
(...), 'group',
)
labels = {
(...),
'group': u'Choose specific group',
}
widgets = {
'group': forms.SelectMultiple(attrs={'class': 'form-control chosen', 'data-placeholder': 'Select group'}),
}
def __init__(self, *args, **kwargs):
super(PaymentForm, self).__init__(*args, **kwargs)
self.prepare()
def prepare(self):
(...)
groups = Group.objects.all()
# here I'm changing names of groups 'test_X' to the tournament title using one to one connection
list_of_proper_names = [g.name if not 'test' in g.name else g.virtual_group.title for g in groups]
# in ok I got proper values (this is list of strings -> group names and Payment titles)
# and here I'm trying to pass only group names and titles
self.fields['group'].initial = list_of_proper_names
但是这不起作用。...我总是在视图中获得REAL组名,因此我仍然得到“ test_1”,“ test_2”等。
即使我在上面的列表理解中更改了这些名称,这种情况仍在发生
我也尝试过
self.fields['group'].queryset
但是在这里我无法传递字符串列表,这是唯一的查询集,因此,如果我再次传递Group.objects.all()
,则会得到结果为“ test_1”,“ test_2”
我不知道如何用付款标题覆盖组名“ test_X”。仍然是相同的id / pk ...,但我只想用相应的(通过一对一字段virtual_group)付款标题重命名它。
(我必须使用test_X,因为密钥必须始终唯一)
我将不胜感激!