[Django]-How to avoid repeated values retrieved from database?

0👍

Use a set rather than an array. It 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})

The basic idea:

  1. Create a set object
  2. Perform a union operation with each search result into the set
  3. Convert the set back to a list and send it to the template

On a side note, I agree with some of the comments in that “form1” is not a great name for a model.

Leave a comment