From fb58ef043cc39d900bb8389855f07087cb0d7920 Mon Sep 17 00:00:00 2001 From: Matt d'Entremont Date: Wed, 4 Mar 2015 17:36:03 -0400 Subject: Add support for serializing models with m2m related fields - In both ManyRelatedField, provide an empty return when trying to access a relation field if the instance in question has no PK (so likely hasn't been inserted yet) - Add relevant tests - Without these changes, exceptions would be raised when trying to serialize the uncreated models as it is impossible to query relations without a PK - Add test to ensure RelatedField does not regress as currently supports being serialized with and unsaved model--- rest_framework/relations.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'rest_framework') diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 0b7c9d86..3a966c5b 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -360,6 +360,10 @@ class ManyRelatedField(Field): ] def get_attribute(self, instance): + # Can't have any relationships if not created + if not instance.pk: + return [] + relationship = get_attribute(instance, self.source_attrs) return relationship.all() if (hasattr(relationship, 'all')) else relationship -- cgit v1.2.3