getting unique id

31 views
Skip to first unread message

Larry Martell

unread,
Nov 23, 2022, 11:58:21 AM11/23/22
to django...@googlegroups.com
I have an app that needs to get a unique ID. Many threads run at the
same time that need one. I would like the IDs to be sequential. When I
need a unique ID I do this:

with transaction.atomic():
max_batch_id =
JobStatus.objects.select_for_update(nowait=False).aggregate(Max('batch_id'))
json_dict['batch_id'] = max_batch_id['batch_id__max'] + 1
status_row = JobStatus(**json_dict)
status_row.save()

But multiple jobs are getting the same ID. Why does the code not work
as I expect? What is a better way to accomplish what I need?

Shaheed Haque

unread,
Nov 23, 2022, 1:43:59 PM11/23/22
to django...@googlegroups.com
Are all the threads in the same Python process? Or the same machine? Do they have to persist across process (or machine) restarts? 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACwCsY54vF6ZK7yy--15hy1u5vxJ%2Bq9Zp_ODGfAX973gPYpecw%40mail.gmail.com.

Larry Martell

unread,
Nov 23, 2022, 3:02:22 PM11/23/22
to django...@googlegroups.com
On Wed, Nov 23, 2022 at 1:43 PM Shaheed Haque <shahee...@gmail.com> wrote:
>
> Are all the threads in the same Python process?

No

> Or the same machine?

No

> Do they have to persist across process (or machine) restarts?

Yes.

Playing around with using F() but still don't have it working as desired.

Thomas Lockhart

unread,
Nov 23, 2022, 3:03:06 PM11/23/22
to django...@googlegroups.com
Why not use the existing Django AutoField?

- Tom

Larry Martell

unread,
Nov 23, 2022, 3:12:45 PM11/23/22
to django...@googlegroups.com
On Wed, Nov 23, 2022 at 3:01 PM Thomas Lockhart <tlockh...@gmail.com> wrote:
>
> Why not use the existing Django AutoField?

Because I have multiple rows with the same batch_id, and also I would
like the batch_ids to be sequential.

The use case is a batch job dashboard. Users run jobs that spawn many
sub jobs. The jobs all record their status in the JobStatus table. The
batch dashboard shows all the sub jobs grouped under their parent job.
The parent job creates a row with a new batch_id, and that is passed
to the sub jobs. They all record their status using that same batch
id, but each in its own row.

Larry Martell

unread,
Nov 28, 2022, 10:33:45 AM11/28/22
to django...@googlegroups.com
I ended up using another table to get the batch_ids from. It works,
but I still wonder how to make it work without a second table.
Reply all
Reply to author
Forward
0 new messages