我的模型看起来像这样:
getMap :: M2 -> Int -> M1
getMap = (fromJust .) . flip M.lookup
现在,从这个模型中,我得到了所有class AddCoffee(models.Model):
user = models.CharField(max_length=50)
coffee_name = models.CharField(max_length=50)
coffee_price = models.CharField(max_length=10)
s:
coffee_name
现在,我想要做的事情(即使有一些与SO密切相关的主题,我也无法找到任何方法):
生成coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True)
len(coffee_names)
s,标签为每个咖啡名称,值为0到50之间的列表。如下所示:
ChoiceField
我怎样才能做到这一点?对于我如何在模型/视图中存储此动态字段后,我的脑子里有些含糊不清。
我试过了:
class RequestCoffeeForm(forms.Form):
coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True)
for name in coffee_names:
forms.ChoiceField(label="{}".format(name),
choices=[x for x in range(51)])
"""
Suppose coffee_names = ["ABC", "DEF"]
I should have two `ChoiceFields` as follows:
ABC = forms.ChoiceField(label="ABC", choices=[x for x in range(51)])
DEF = forms.ChoiceField(label="DEF", choices=[x for x in range(51)])
"""
然后在我的视图中调用:
class RequestCoffeeForm(forms.Form):
coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True)
for name in coffee_names:
name = forms.ChoiceField(label="{}".format(name), choices=((str(x), x) for x in range(51)))
然后在我的模板中:
@login_required(login_url="login/")
def request_coffee_page(request):
form = RequestCoffeeForm(request.POST or None)
return render(request, "request_coffee.html", {'form': form})
以上仅打印最后一个coffee_name。我怎样才能打印出来?
答案 0 :(得分:0)
class RequestCoffeeForm(forms.Form):
COFFEE_CHOICES = []
coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True)
for name in coffee_names:
COFFEE_CHOICES.append((str(name).lower(), str(name)))
forms.ChoiceField(choices=CHOICES_LIST)
choices
必须是iterable of 2-tuples。有关示例,请参阅here。
答案 1 :(得分:0)
我没有时间尝试,但AFAICT 可能会工作:
var that = this;
data.forEach(function (eachObj) {
console.log("firms check!");
console.log(that.firms); // not working
a = a + eachObj.income;
eachObj.name = that.firms[data.firmid - 1].name; // wont work
});