我想按username
进行搜索,但我的代码设置方式只能在用户模型中按id
进行搜索。如何按username
进行搜索?它可能很难,但我没有看到它是如何完成的。
模型
class Incident(models.Model):
incident_id = models.CharField(max_length=1000)
user_id = models.ForeignKey(User)
形式
<form method='GET' action='/search_incidents/'>
<div class="row">
<div class="form-group col-md-3">
<label>Incident ID</label>
<input type="text" name="incident_id" value="{{ incident_id_query }}" class="form-control"/>
</div>
<div class="form-group col-md-3">
<label>User ID</label>
<input type="text" name="user_id" value="{{ user_id_query }}" class="form-control"/>
</div>
</div>
</form>
查看
@login_required
def search_incidents(request):
if request.method == 'GET':
incident_id_query = request.GET.get('incident_id')
user_id_query = request.GET.get('user_id')
try:
incident_id = str(incident_id_query)
except ValueError:
incident_id = None
try:
user_id = str(user_id_query)
except ValueError:
user_id = None
list = [incident_id,user_id]
if all(x is None for x in list): #check if `list` contains only None
incident_list = None #this in case the query comes back empty
else: #perform query
incident_list = Incident.objects.filter(incident_id=incident_id).filter(user_id=user_id)
return render(request, 'search_incidents.html', {
'incident_list' : incident_list
})