Using Django-RQ, a model query only works on second run

99 Views Asked by At

Using Django-RQ (v2.3.0) querying the (PostgreSQL) database only works when done twice. This is the setup:

models.py:

class AnalysisResult(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    public_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)

tasks.py:

@job(os.getenv("REDIS_QUEUE_NAME", "default"))
def update_progress_in_db(result_id: UUID):
    # FIXME This query only works on the second try when we run this here inside the rqworker?!
    try:
        tmp_record = AnalysisResult.objects.get(public_id=result_id)
    except (AnalysisResult.DoesNotExist, AnalysisResult.MultipleObjectsReturned) as e:
        # Always getting the exception here!
        logger.error("Error retrieving tmp_record with id={}: {}.".format(result_id, e))
    except Exception as ex:
        logger.error("General error while retrieving tmp_record: {}".format(ex))

    try:
        record = AnalysisResult.objects.get(public_id=result_id)
        logger.debug("result record: {}".format(record)) # Working fine.
    except (AnalysisResult.DoesNotExist, AnalysisResult.MultipleObjectsReturned) as e:
        # Never getting this exception.
        logger.error("Error updating progress status with id={}: {}.".format(result_id, e))
    except Exception as ex:
        logger.error("General error while updating progress status: {}".format(ex))

Running AnalysisResult.objects.get(public_id=result_id) in a django-admin shell always works fine on the first try. And I would very much like to not use the above workaround of trying to query the record twice. It just feels too dirty.

Pointers on what might be missing here are appreciated.

0

There are 0 best solutions below