mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-23 06:29:58 +03:00
Do not rely that primary_key
will always be first field,
Add support for specifying `fields = ('pk',)` to serialize the primary key field (no matter how the field is actually called)
This commit is contained in:
parent
027c9079f6
commit
b53a2f74ed
|
@ -126,11 +126,16 @@ class BaseSerializer(Field):
|
|||
for key, val in fields.items():
|
||||
if key not in ret:
|
||||
ret[key] = val
|
||||
if value.source.primary_key:
|
||||
pk_field = key
|
||||
|
||||
# If 'fields' is specified, use those fields, in that order.
|
||||
if self.opts.fields:
|
||||
new = SortedDict()
|
||||
for key in self.opts.fields:
|
||||
if key == 'pk':
|
||||
# User requested the 'pk', use the primary key found
|
||||
new[key] = ret[pk_field]
|
||||
new[key] = ret[key]
|
||||
ret = new
|
||||
|
||||
|
@ -344,12 +349,11 @@ class ModelSerializer(Serializer):
|
|||
fields += [field for field in opts.many_to_many if field.serialize]
|
||||
|
||||
ret = SortedDict()
|
||||
is_pk = True # First field in the list is the pk
|
||||
|
||||
for model_field in fields:
|
||||
if is_pk:
|
||||
if model_field.primary_key:
|
||||
# Django requires models to have only one primary_key so this should be safe
|
||||
field = self.get_pk_field(model_field)
|
||||
is_pk = False
|
||||
elif model_field.rel and nested:
|
||||
field = self.get_nested_field(model_field)
|
||||
elif model_field.rel:
|
||||
|
|
Loading…
Reference in New Issue
Block a user