Skip to content

Bigint coerce to string missing #9733

Closed

Description

@HoodyH

I've found this setting but there is no counterpart for Bigint

COERCE_DECIMAL_TO_STRING

JSON does not have a native BigInt type — it is safely precise for integers only up to 2⁵³ − 1 (i.e. 9,007,199,254,740,991). Beyond this threshold, numbers lose precision and may be silently truncated or rounded when parsed in JavaScript or other languages.

It depends on the json library implementation, this particular issue doesn’t happen in Python but it’s not consistent across all languages JSON libraries

Why DRF test frontend works?
Because it uses FormData, basically it is all string data, and since the server side render is handled by python no bigint errors occour

Resources:
Conversion problems

Since javascript is a lot used, this is an issue that have to be addressed in my opinion, i know that the bigint problem with ids will happen only at very large scale and probably a lot of people will never encounter this, but if we find a solution it would be wonderfull.

COERCE_BIGINT_TO_STRING

I suggest to add a flag like this

Activity

  1. browniebroke commented on Jul 6, 2025

    @browniebroke
    Collaborator

    Seems sensible to me. As it's becoming more prevalent since the introduction of DEFAULT_AUTO_FIELD in Django 3.2, I'd say it qualifies with our policy to "track the continued development of Django versions".

  2. HoodyH commented on Aug 25, 2025

    @HoodyH
    ContributorAuthor

    Sorry for the late reply, I've only just found the time to work on this issue

    To resolve this problem i want to avoid creating special logic on IntegerField using isinstance or similar. Since django.models.BigIntegerField exists, we can map it directly. In my opinion, this makes the code more maintainable, but I’m eager to hear your thoughts.

    class BigIntegerField(IntegerField):
    
        default_error_messages = {
            'invalid': _('A valid biginteger is required.'),
            'max_value': _('Ensure this value is less than or equal to {max_value}.'),
            'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
            'max_string_length': _('String value too large.')
        }
    
        def __init__(self, coerce_to_string=None, **kwargs):
            super().__init__(**kwargs)
    
            if coerce_to_string is not None:
                self.coerce_to_string = coerce_to_string
    
        def to_representation(self, value):
            coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_BIGINT_TO_STRING)
    
            if value is None:
                if coerce_to_string:
                    return ''
                else:
                    return None
    
            if coerce_to_string:
                return str(value)
            else:
                return int(value)

    the coerce_to_string implementation is as similar as possible to Decimal

    update in serializers.py

     serializer_field_mapping = {
            models.AutoField: IntegerField,
            models.BigAutoField: BigIntegerField,
            models.BigIntegerField: BigIntegerField,
            ...
        }

    In the encoding section of the settings, COERCE_BIGINT_TO_STRING has been added. By default, it is False, so the current behavior will be maintained.

        # Encoding
        'UNICODE_JSON': True,
        'COMPACT_JSON': True,
        'STRICT_JSON': True,
        'COERCE_DECIMAL_TO_STRING': True,
        'COERCE_BIGINT_TO_STRING': False,
        ...

    The code has been tested also on one of my production project and i have created the test case in the repo and updated the documentation.

    If it's all ok probably in the next days after re-checking all i will submit the pr.

  3. browniebroke commented on Sep 5, 2025

    @browniebroke
    Collaborator

    To resolve this problem i want to avoid creating special logic on IntegerField using isinstance or similar. Since django.models.BigIntegerField exists, we can map it directly. In my opinion, this makes the code more maintainable, but I’m eager to hear your thoughts.

    I'm not sure we need that distinction, let me outline where I am with my thinking...

    While I can see the argument for keeping things separate, I can also see the case where people were explicitly defining their field IntegerField (without relying on the auto-mapping or on non model serializers), and would need to update their code to use BigIntegerField:

     class MyCustomSerializer(serialziers.Serializer):
    -    my_big_int = serializers.IntegerField()
    +    my_big_int = serializers.BigIntegerField(coerce_to_string=True)

    Would also make some detail "leak" to the frontend: regular integers would be represented as integer while bigint would be represented as string. I think as a API consumer I'd rather have consistent types across all endpoints, but I may be missing something here...

    The counter argument to my thinking, supporting the idea of keeping it separate, it that the JS app will need to know that the number is a bigint and having a string returned would be the signal to trigger some special handling.

    I haven't came across this problem yet, so I have a few questions to understand more the consumer side: once the bigint is returned as string, what does the JS app need to do? How is the consumer supposed to work with that number? Is it the case of instantiating a BigInt from the string?

  4. HoodyH commented on Sep 6, 2025

    @HoodyH
    ContributorAuthor

    I came across this problem when I tried to use Snowflake IDs as IDs for database tables (they’re not safe integers in JavaScript). I looked at how some well-known websites handle the bigint problem. For example, Facebook, Twitter, Discord, Riot Games all use Snowflake IDs or some sort of bigint, and in their APIs these IDs are represented as strings. (Twitter, actually, is the only one that returns both a numeric ID and a string ID, but they strongly recommend using the string version)

    In JavaScript (or any other language), you only need to use BigInt("9007199254740991") when you have to perform operations on the number. In the case of IDs, keeping them as strings is sufficient, in most other cases you already made the computation in the backend (like finance or timestamps). Another use case that I used is large counters, e.g. analytics like packets sent. In those cases, the only operation you typically perform on the client side is scaling the value to represent it in the shortest possible string (1K, 10.4M).

    Technical problem aside, there is also a formal one: JSON does not have a native BigInt type. So delivering a number bigger than 9,007,199,254,740,991 is technicaly wrong (still works in most cases).

    I've discused with @ulgens, you can find more information in discussion 9722 and see my workaround

    Would also make some detail "leak" to the frontend: regular integers would be represented as integer while bigint would be represented as string. I think as a API consumer I'd rather have consistent types across all endpoints, but I may be missing something here...

    I think the main reason BigIntField wasn’t introduced earlier is that Python handles all integers in a single type, even though the majority of languages separates it in more types.
    Let’s suppose we call our API from C++; we need to know exactly which type of integer we used in our database (int8_t, int32_t, int64_t, or unsigned) to allocate the correct amount of memory without using long long everywhere. Therefore, it is still necessary to document the size of the IntegerField returned by the API.

    While I can see the argument for keeping things separate, I can also see the case where people were explicitly defining their field IntegerField (without relying on the auto-mapping or on non model serializers), and would need to update their code to use BigIntegerField:

    This is true: people who want to use the framework to its maximum should update their code, but it’s not mandatory, it works anyway (for small scales) even if you are technically using it incorrectly. We can add more information about this corner case in the documentation, it could be useful.

    My first implementation was integrated in IntegerField() but the code seemed to me complicated to read (too many conditions), so I changed to the one proposed. But as I said, I really want to hear your suggestions and in that case I can update it.

  5. browniebroke commented on Oct 9, 2025

    @browniebroke
    Collaborator

    I had more thought about the need for a distinct field for BigInt. I often think of serializers as the DRF equivalent of forms in Django and serializers fields as forms fields. As I integrated with Django's forms API, I realised that there is a single forms.IntegerField, used for both model types, and there is no forms.BigIntegerField.

  6. added this to the 3.17 milestone on Dec 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions