How to avoid duplicate values ​​retrieved from the database?

I have two models. One model with a name field and others with a key skills field and a foreign key for model 1. I saved the values ​​in the fields. When I perform a search using key skills, it should bring names with the fields entered. When I search for c and C ++, if the name contains both c and C ++, when I get the names based on the search, the name is repeated twice. I do not want to repeat myself. 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>

Can anyone help me? .. thanks in advance

+4
source share
1 answer

Use a set, not an array. This will avoid duplicate entries.

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})

Main idea:

  • Create specified object

, , "form1" .

0

All Articles