Wednesday, May 27, 2020

Looking for a solution? Calculating index/offset of a particular record?

I'm trying to optimize a few different things.

I am looking to try to change this into a more database driven routine, instead of having to iterate through each and every record.  While not time consuming (overall), I would like to try to make it a bit cleaner…

Effectively I am calculating which record the user is actually looking at in the gallery.  The UUID is based into the view, and the view then has to figure out it's image XX out of YYY.

 for counter, data in enumerate(catalog_qs, start=1):
     if str(data.uuid) == e_uuid:
         context["page"] = counter
         break

I generalized it to this:

def return_offset_uuid(sorder, fpath, tuuid):
    """
        Fetch specific database values only from the database
    """
    entries = index_data.objects.exclude(ignore=True).exclude(delete_pending=True).filter(
        fqpndirectory=fpath.lower().strip()).order_by(*SORT_MATRIX[sorder])
    tpk = entries.filter(uuid=tuuid.strip())[0].pk
    count = entries.filter(pk__lte=tpk).count() - 1
    #answer = user.answer_set.filter(question=question).get()
    # return user.answer_set.filter(pk__lte=answer.pk).count() - 1
    return count


Which *seemed* to work, except it didn't.  Yes, I got results:

>>> return_offset_uuid(0, album, "c0543ce7-d156-430d-b08a-5f7379b6e246")    # 1
1
>>> return_offset_uuid(0, album, "519f5b9c-e4f4-44e1-aa82-f36aed98e6a9")    # 31
4905
>>> return_offset_uuid(0, album, "754fcb51-c3ad-417d-b317-b86305597ae9")    # 61
5044
>>> return_offset_uuid(0, album, "b85f18e0-aa17-4192-9c0f-a363d82fa127")    # 91
81
>>> return_offset_uuid(0, album, "fe750266-5fb6-467a-929e-c752fa2091ac")      # 121
108
>>> return_offset_uuid(0, album, "51d5ea79-1859-402b-85ff-ae3b2adf7173")      # 5535
4885

Looking at it, entry "AAAA.jpg" is added, it'll have a larger PK than "ZZZ.jpg" which was added two months ago.

Is there a better way to do this?  I'll keep the for loop if I have to…

- Benjamin


No comments:

Post a Comment