Is there any way for using fields value +1 inplace in bulk_create

I have some code for count reference number. if row exist , reference_count += 1,else reference_count=1
here is code .

        if not RawFileReference.objects.filter(
            raw_file_name=image_info["raw_file_name"]
        ).exists():
            raw_file = RawFileReference.objects.create(
                **{"raw_file_name": image_info["raw_file_name"], "reference_count": 1}
            )
        else:
            raw_file = RawFileReference.objects.get(
                raw_file_name=image_info["raw_file_name"]
            )
            raw_file.reference_count += 1
            raw_file.save()

but I want to rewrite code with bulk_create,how to implement +1 feature?

I believe you could use bulk_create along with F expressions, though I don’t know if this feature is yet available, I only have saw this being discussed on this forum.

EDIT:
It’s indeed not available, found the discussion.


But you can replace your code with get_or_create, that essentially does the same thing. It would look like:

raw_file, created = RawFileReference.objects.get_or_create(
    raw_file_name=image_info["raw_file_name"],
    defaults={"reference_count": 0},
)
raw_file.reference_count += 1
raw_file.save(update_fields=("reference_count",))

Hope this helps.

1 Like

thank for your help,but I intend to reduce network IO, so I want to use batch operation

You can’t do it through the ORM, because you need to execute the extra query to determine whether or not to add 1 to the reference count.

If you’re looking to do this to reduce network IO, I’d suggest creating this as a stored procedure in the database. It’s not going to reduce the number of queries being executed, but it will prevent those additional queries from generating network traffic.