Django:表单查询数据库 [英] Django: form to query database
本文介绍了Django:表单查询数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望用户能够执行以下查询:
I want a user to be able to perform the following query:
获取所有的人员,没有Phd,与合同内的全日制合同两个日期。
Fetch all the people, without Phd, with full time contract with a contract within two dates.
在Django中翻译:
that translates in Django:
Contract.objects.filter(
person__is_doctor = False,
type_contract = 'full',
starting_date__gte = start_date,
ending_date__lte = end_date
)
如何使表单/视图/模板允许用户同时输入 start_date 和 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?
模型
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? 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>
这篇关于Django:表单查询数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文