About Creating IDs for API Elements Dynamically

In ReactJS, all your rendered lists need to have unique IDs for the key attributes. When your lists come from the settings, file system, or a text file, create the IDs dynamically, for example, using the hashlib library:

# rest_api/views.py
from hashlib import blake2b
from django.utils.encoding import force_bytes
from rest_framework.response import Response

def file_content(request, file_path):
    items = []
    with open(file_path, encoding="utf-8") as fp:
        for item in json.load(fp):
            h = blake2b(digest_size=8)
            h.update(force_bytes(item["title"]))
            item["id"] = h.hexdigest()
            items.append(item)
    data["results"] = items
    return Response(data)

With hashlib.blake2b you can adjust the hash size.

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 Python 3 JavaScript ReactJS