I have a django app with several models, some with foreignkeys to each other, nothing particularly complicated. All models have a pk automatically provided by a BigAutoField as that is what is defined in the settings.
I have now added api views using DRF ModelViewSets in order to get json for use in some javascript in the browser. However when I turn the json string into a javascript object the pk (field is called id) gets treated as a number (as expected). However, plenty of the pk are larger than javascript number's max safe value so the last digits are displayed as zeros. This makes the pk useless for selecting or comparing items. I'm fairly new to both DRF and Javascript, but I feel like this is a very common use case so I feel there is probably an accepted way of handling this.
As far as I can tell there are several ways of doing this:
- Use
id = serializers.CharField()
for all model serializers and use string comparisons in JS. - Migrate all models to have a
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
field as their primary key. - Use
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
instead as I will never have anywhere close to 2147483647 entries in any table.
Is this correct? Am I missing something? How are pks usually handled in a separate API/SPA setup?
CodePudding user response:
Use
id = serializers.CharField()
for all model serializers and use string comparisons in JS.
Yes, just use strings. Surrogate primary keys never need to be used as numbers in calculations. This is very common for JSON that should be parsed using normal JSON.parse
, not something specifically built to deal with bigints.