我有两个型号。一个具有名称字段的模型,另一个具有关键技能字段和model1的外键。我已将值存储到字段中。当我使用关键技能进行搜索时,它应该带有输入字段的名称。当我搜索c和c ++时,如果名称包含c和c ++,当我根据搜索检索名称时,名称会重复两次。我不想再重复。 models.py
class form1(models.Model):
name=models.CharField(max_length=20)
def __unicode__(self):
return self.name
class form2(models.Model):
keyskills=models.CharField(max_length=20)
na=models.ForeignKey(form1)
def __unicode__(self):
return self.keyskills,self.na
views.py
def add(request):
if request.method=='POST':
na=request.POST.get('name1')
k=request.POST.get('key1')
v1=form1(name=na)
v1.save()
v2=k.split(",")
for i in v2:
if i:
form2(keyskills=i,na_id=v1.id).save()
return HttpResponseRedirect('/add')
else:
s=form2.objects.all()
return render(request,"search.html",{'s':s})
def search(request):
var=""
arr=[]
if request.method=='POST':
s1=request.POST.get("input1")
s1=s1.split(",")
for i in s1:
if i :
arr+=form2.objects.filter(keyskills=i)
var=arr
return render(request,"searchresult.html",{'var1':var})
searchresult.html
<html>
<head>
</head>
<body>
<div id="div1">
{% for i in var1 %}
<p>{{i.na.name}}</p><br>
{% endfor %}
</div>
<form action="." method="post">{% csrf_token %}
<input type="text" name="input1">
<input type="submit" value="search">
</form>
</body>
</html>
任何人都可以指导我吗?...提前感谢
答案 0 :(得分:0)
使用集而不是数组。它将避免重复的条目。
def search(request):
from sets import Set
var=""
# create set object
set = Set()
if request.method=='POST':
s1=request.POST.get("input1")
s1=s1.split(",")
for i in s1:
if i :
# |= is the set union operator
set |= Set(form2.objects.filter(keyskills=i))
# convert set back to list
var=list(set)
return render(request,"searchresult.html",{'var1':var})
基本理念:
在旁注中,我同意一些评论,因为“form1”不是模型的好名字。