I came across this issue calling the following and FK fields with _id are 
ignored:
serialize('json', ...., fields=['title', 'state_id']). 

State is a ForeignKey on my queryset. I can perform fields=['title', 
'state'] and I get serialization correctly of {'state': int}. However, if I 
specify fields=['state_id'] then the serialization completely ignores that 
field. It would be nice if we could serialize foreign keys on either 
field.name or field.attname. 

I wrote a hack to make it work myself but it breaks the non-id use case.

def start_serialization(self):
for field in [x for x in self.selected_fields if '_id' in x]:
self.selected_fields.append(field.replace('_id', ''))
super().start_serialization()

def handle_fk_field(self, obj, field):
if not self.use_natural_foreign_keys and not hasattr
(field.remote_field.model, "natural_key"):
self._current[field.attname] = getattr(obj, field.attname)
else:
return super().handle_fk_field(obj, field)

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/6b961b2f-5ef5-4822-a732-ac5843f5b0e3n%40googlegroups.com.

Reply via email to