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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 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 4.x Django 3.2 Django 2.2 Python 3 JavaScript ReactJS