Dealing with reverse relationships

This commit is contained in:
Tom Christie 2014-09-12 21:32:20 +01:00
parent 4fceceae7d
commit afb28a44ad
2 changed files with 28 additions and 7 deletions

View File

@ -157,7 +157,7 @@ class Serializer(BaseSerializer):
def __init__(self, *args, **kwargs):
self.context = kwargs.pop('context', {})
kwargs.pop('partial', None)
kwargs.pop('many', False)
kwargs.pop('many', None)
super(Serializer, self).__init__(*args, **kwargs)
@ -423,9 +423,9 @@ class ModelSerializer(Serializer):
for accessor_name, relation_info in info.reverse_relations.items():
if accessor_name in self.opts.fields:
if self.opts.depth:
ret[field_name] = self.get_nested_field(*relation_info)
ret[accessor_name] = self.get_nested_field(*relation_info)
else:
ret[field_name] = self.get_related_field(*relation_info)
ret[accessor_name] = self.get_related_field(*relation_info)
return ret
@ -444,7 +444,7 @@ class ModelSerializer(Serializer):
Note that model_field will be `None` for reverse relationships.
"""
class NestedModelSerializer(ModelSerializer):
class NestedModelSerializer(ModelSerializer): # Not right!
class Meta:
model = related_model
depth = self.opts.depth - 1

View File

@ -73,9 +73,9 @@ class OneToOneTargetModel(models.Model):
class RelationalModel(models.Model):
foreign_key = models.ForeignKey(ForeignKeyTargetModel)
many_to_many = models.ManyToManyField(ManyToManyTargetModel)
one_to_one = models.OneToOneField(OneToOneTargetModel)
foreign_key = models.ForeignKey(ForeignKeyTargetModel, related_name='reverse_foreign_key')
many_to_many = models.ManyToManyField(ManyToManyTargetModel, related_name='reverse_many_to_many')
one_to_one = models.OneToOneField(OneToOneTargetModel, related_name='reverse_one_to_one')
RELATIONAL_FLAT_REPR = """
@ -160,3 +160,24 @@ class TestSerializerMappings(TestCase):
model = RelationalModel
depth = 1
self.assertEqual(repr(TestSerializer()), HYPERLINKED_NESTED_REPR)
# def test_flat_reverse_foreign_key(self):
# class TestSerializer(serializers.ModelSerializer):
# class Meta:
# model = ForeignKeyTargetModel
# fields = ('id', 'name', 'reverse_foreign_key')
# print repr(TestSerializer())
# def test_flat_reverse_one_to_one(self):
# class TestSerializer(serializers.ModelSerializer):
# class Meta:
# model = OneToOneTargetModel
# fields = ('id', 'name', 'reverse_one_to_one')
# print repr(TestSerializer())
# def test_flat_reverse_many_to_many(self):
# class TestSerializer(serializers.ModelSerializer):
# class Meta:
# model = ManyToManyTargetModel
# fields = ('id', 'name', 'reverse_many_to_many')
# print repr(TestSerializer())