今天我正在尝试获取并打印所有用户选择“Value1”的用户电子邮件。
这就是我的model.py的样子:
from django.db import models
class Vartotojas(models.Model):
email = models.EmailField()
option = models.CharField(max_length=30)
Forms.py:
from django import forms
from emailai.models import Vartotojas
class VartotojasForm(forms.Form):
email = forms.EmailField(max_length=100)
my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
def save(self):
mymodel = Vartotojas(
email=self.cleaned_data['email'],
option=self.cleaned_data['my_field'],
)
mymodel.save()
最后我的views.py“
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from emailai.models import Vartotojas
from renginiai.forms import VartotojasForm
def name(request):
if request.method == 'POST':
form = VartotojasForm(request.POST)
if form.is_valid():
a = Vartotojas.objects.filter(option="u'Value1'") # How to do it right?
# Now How To Get those object emails?
new_user = form.save()
return render(request, "Vartotojas-result.html", {
'form': form, #BLABLABLA,
})
else:
form = VartotojasForm()
return render(request, "Vartotojas-form.html", {
'form': form,
})
我在views.py中评论了我的问题。我希望你能帮助我。提前谢谢!
我用getlist重写我的代码。现在它看起来像这样:
if form.is_valid():
email = form.cleaned_data['email']
option = request.POST.getlist('my_field')
new_user = form.save(email, option)
forms.py:
email = forms.EmailField(max_length=100)
my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
def save(self, email, option):
mymodel = Vartotojas(
email=email,
option = option,
)
mymodel.save()
如你所见,我粘贴了最重要的地方。顺便说一句,用户可以选择2个值,这就是我使用复选框的原因。但它仍然不起作用。
答案 0 :(得分:2)
我相信您想要使用values_list
属性,如下所示:
Vartotojas.objects.filter(option=u"Value1").values_list("email", flat=True)
获取所有电子邮件地址的列表。如果您尚未预防重复,则可能还需要distinct()
。请注意,查看ModelForms:看起来这样可以为您节省相当多的时间/代码来处理这个问题。您可以根据Vartotojas
对象创建ModelForm,而不必编写您拥有的显式save()
方法。