0

I have the following python3 script running on an ubuntu server.

def obtener_articulo_aleatorio(cursor, date, categorias_utilizadas):
        if categorias_utilizadas:
            # Construir la consulta SQL con categorías utilizadas
            query = "SELECT * FROM ASINDUMPTEMP WHERE publicado = 0 AND date ='%s' AND browsenode NOT IN (%s) ORDER BY RAND() LIMIT 1"
            categorias_string = ','.join(["'{}'".format(c) for c in categorias_utilizadas])
            params = (date.today(), categorias_string)
        else:
            # Construir la consulta SQL sin categorías utilizadas
            query = "SELECT * FROM ASINDUMPTEMP WHERE publicado = 0 AND date = %s ORDER BY RAND() LIMIT 1"
            params = (date.today(),)
      
        cursor.execute(query, params)
        record = cursor.fetchone()
        
        # Si no se encuentra un registro, obtener uno aleatorio
        if record is None and categorias_utilizadas:
            cursor.execute("SELECT * FROM ASINDUMPTEMP WHERE publicado = 0 AND date = %s ORDER BY RAND() LIMIT 1", (date.today(),))
            record = cursor.fetchone()
        return record

I'm pulling the list as the extracted articles are published in another function.

categorias_utilizadas = [] categorias_utilizadas.append(record[4])

The problem I have is that when the query is made and categories are added to the list so that they are not repeated, the returned query "ignores" the NOT IN.

If I print the query before executing, it is correct, since if I execute the query in Mysql it works without problems.

Why pass it like this in python, right? Any problem or error that I am getting?

Thanks a lot! Aaron

I want that once an article is removed, the category of the article is added to the list. When the next article is to be extracted, it does not belong to the same category as the previous ones.

The categories are entered in a separate function, but it works correctly since if I print the list, the entered categories are printed.

  • no it isn't lets say you have `1,2,3,4` you could will produce `IN ('1,2,3,4')` as one string, that is why you don't need for the date apostrophes around the %s they are automatically addeed – nbk Jul 18 '23 at 19:11

0 Answers0