Django Rest Framework: Create List Model with custom data

Assume that I want to create multiple model objects and I want to add some generated unique data to all of them when saving.

So if post something like this to an endpoint:

[
   {
      "createDate":"now"
   },
   {
      "createDate":"now"
   }
]

The response should be something like:

[
   {
      "createDate":"now",
      "uid":"1"
   },
   {
      "createDate":"now",
      "uid":"2"
   }
]

I have created a ViewSet for this and generate the necessary fields in the perform_create ovveride method:

    def perform_create(self, serializer):
        unique_ids = ReleModuleConfig.objects.values_list('uid', flat=True)
        uid = generate_random_id(unique_ids)
        serializer.save(added_by=self.request.user, updated_by=self.request.user, uid=uid)

However when I save this, the same uid is set for all of the objects. So the response is:

[
   {
      "createDate":"now",
      "uid":"1"
   },
   {
      "createDate":"now",
      "uid":"1"
   }
]

How could I generate unique fields and inject it into the serializer if I have multiple objects?

I know that there is already an ID unique field by default on most tables, but I have to generate QR codes and other things as well, I just removed that from this example to make it easier to understand.

Back to Top