[Answered ]-Check duplicate data in database using Django

1👍

Just change the query:

from

query = """
        SELECT date_travel FROM tev_incoming
        WHERE name = %s
        AND date_travel LIKE %s;
    """

to

query = """
        SELECT date_travel FROM tev_incoming
        WHERE name = %s
        AND date_travel LIKE %%%s%%;
    """

so now, it would match the date anywhere in the string instead for searching for it from the left only.

Hope this would help.

0👍

The problem is the location of the else statement, it will only go over the first date in individual_dates and depending on that go to the if or else statement. If you move the else statement to after the for loop it will work because it goes through all dates before coming to the conclusion that the date is unique.

@csrf_exempt
def item_add(request):
    employeename = request.POST.get('EmployeeName')
    travel_date = request.POST.get('DateTravel')

    # Split the date string into individual dates
    individual_dates = travel_date.split(',')

    for date in individual_dates:
        cleaned_date = date.strip()
 
        
        query = """
            SELECT date_travel FROM tev_incoming
            WHERE name = %s
            AND date_travel LIKE %s;
        """

        with connection.cursor() as cursor:
            cursor.execute(query, [employeename, cleaned_date])
            results = cursor.fetchall()
             
        if results:
            return JsonResponse({'data': 'error', 'Duplcate date travel':results})
        
    return JsonResponse({'data': 'success', 'message': "Unique travel and name"})

Leave a comment