[英]Django: form to query database
I want a user to be able to perform the following query: 我希望用户能够执行以下查询:
Fetch all the people, without Phd, with full time contract with a contract within two dates. 在没有博士学位的情况下,用两个日期之内的合同获得全职合同的所有人。
that translates in Django: 在Django中翻译:
Contract.objects.filter(
person__is_doctor = False,
type_contract = 'full',
starting_date__gte = start_date,
ending_date__lte = end_date
)
How can I make a form/view/template to allow the user enter both start_date and end_date and show the results? 如何制作表格/视图/模板以允许用户输入start_date和end_date并显示结果?
models 楷模
class Person(models.Model):
name = models.CharField(max_length=32)
surname = models.CharField(max_length=32)
address = models.CharField(max_length=32)
is_doctor = models.NullBooleanField(blank=True, verbose_name=_(u"Phd?")
TYPE_CONTRACT = (
('PT', 'Partial time'),
('FC', 'Full contract')
)
class Contract(models.Model):
person = models.ForeignKey(Person) #person hired
type_contract = models.CharField(max_length = 9, blank = True, choices = TYPE_CONTRACT)
starting_date = models.DateField(blank = True, null = True)
ending_date = models.DateField(blank = True, null = True)
First, I would refactor the Contract
model to better encapsulate the choices, and also, why would a contract allow null values for the start and end dates? 首先,我将重构
Contract
模型以更好地封装选择,并且,为什么合同在开始日期和结束日期允许空值? That seems odd to me from a business logic standpoint. 从业务逻辑的角度来看,这对我来说似乎很奇怪。
class Contract(models.Model):
PT = 'Part Time'
FC = 'Full Contract'
CONTRACT_CHOICES = (
('PT', PT),
('FC', FC)
)
person = models.ForeignKey(Person)
type_contract = models.CharField(max_length=9, choices=CONTRACT_CHOICES,
default=PT)
starting_date = models.DateField()
ending_date = models.DateField()
# view
from django.shortcuts import render
from .forms import ContactForm
def filter_contracts(request):
form = ContractForm(request.POST or None)
contracts = None
if request.method == 'POST':
if form.is_valid():
# encapsulating the contract values means you don't have to
# hand-code them in the query so your code stays DRY
contracts = Contract.objects.filter(person__is_doctor=False,
type_contract=Contract.FC,
starting_date__gte=form.cleaned_data.get('starting_date'),
ending_date__lte=form.cleaned_data.get('ending_date'))
# you might want to specify an order_by here
return render(request, 'your_template.html', {'form': form,
'contracts': contracts})
# template
<form action="." enctype="application/x-www-form-urlencoded" method="post">
<ol>
{{ form.as_ul }}
</ol>
{% csrf_token %}
<button type="submit">Search</button>
{% if contracts %}
<table>
{% for contract in contracts %}
<tr>
<td>{{ contract.person }}</td>
<td>{{ contract.type_contract }}</td>
<td>{{ contract.starting_date }}</td>
<td>{{ contract.ending_date }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
This is the main idea, additionally you will have to check if start_date and end_date are actually in cleaned_data and take that into account when using filter(). 这是主要思想,另外,您还必须检查start_date和end_date是否实际上在cleaned_data中,并在使用filter()时将其考虑在内。
form 形成
class MyForm(forms.Form):
start_date = forms.DateField(initial=datetime.date.today)
end_date = forms.DateField(initial=datetime.date.today)
view 视图
def my_view(request):
contracts = Contract.objects.filter(person__is_doctor=False, type_contract='full')
# if this is a POST request take start_date and end_date into account
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
contracts = contracts.filter(starting_date__gte=form.cleaned_data.get('start_date'), ending_date__lte=form.cleaned_data.get('end_date'))
else:
form = MyForm()
# do everything else that you need to do before returning a response
return render_to_response('template.html', locals(), context_instance=RequestContext(request))
template 模板
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
{% for contract in contracts %}
{{ contract.person }}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.