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:
Pavel Savchenko 2012-11-01 08:36:26 +02:00
parent 027c9079f6
commit b53a2f74ed

View File

@ -126,11 +126,16 @@ class BaseSerializer(Field):
for key, val in fields.items(): for key, val in fields.items():
if key not in ret: if key not in ret:
ret[key] = val ret[key] = val
if value.source.primary_key:
pk_field = key
# If 'fields' is specified, use those fields, in that order. # If 'fields' is specified, use those fields, in that order.
if self.opts.fields: if self.opts.fields:
new = SortedDict() new = SortedDict()
for key in self.opts.fields: 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] new[key] = ret[key]
ret = new ret = new
@ -344,12 +349,11 @@ class ModelSerializer(Serializer):
fields += [field for field in opts.many_to_many if field.serialize] fields += [field for field in opts.many_to_many if field.serialize]
ret = SortedDict() ret = SortedDict()
is_pk = True # First field in the list is the pk
for model_field in fields: 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) field = self.get_pk_field(model_field)
is_pk = False
elif model_field.rel and nested: elif model_field.rel and nested:
field = self.get_nested_field(model_field) field = self.get_nested_field(model_field)
elif model_field.rel: elif model_field.rel: