Okay, that seems sane.

On 15 January 2013 12:40, eofs <notifications@github.com> wrote:

> In rest_framework/serializers.py:
>
> > @@ -369,6 +371,24 @@ class ModelSerializer(Serializer):
> >      """
> >      _options_class = ModelSerializerOptions
> >
> > +    def get_reverse_fields(self, opts, fields):
> > +        # Construct a list of all relations
> > +        relations = []
> > +        relations += [obj for obj in opts.get_all_related_objects() if obj.field.serialize]
> > +        relations += [obj for obj in opts.get_all_related_many_to_many_objects() if obj.field.serialize]
> > +
> > +        # Construct a list of intermediate models
> > +        exclude = []
> > +        for field in fields:
> > +            if field.rel and  hasattr(field.rel, 'through'):
> > +                exclude.append(field.rel.through)
> > +        # Intermediate models from reverse relations
> > +        for rel in relations:
> > +            if rel.field.rel and hasattr(rel.field.rel, 'through'):
> > +                exclude.append(rel.field.rel.through)
>
> Without exclusion serializer would include forward relation twice: Normal
> relatation and reverse relation via intermediate model.
>
> class Genre(models.Model)
>   pass
>
> class Song(models.Model)
>    genres = models.ManyToMany(Genre, through='SongGenre')
>
> class SongGenre(models.Model)
>    song = models.ForeignKey(Song)
>    genre = models.ForeignKey(Genre)
>    is_main = models.Boolean()
>
> class SongSerializer(ModelSerializer)
>   class Meta:
>     model = Song
>     include_reverse_relation = True
>
> With this setup SongSerializer will display genre field as expected but
> also genre_set field, which is just a reverse relation from SongGenremodels
> ForeignKey(Song) field. So my code currently excludes all intermediate
> models if they are specified in models forward relation fields.
>
> —
> Reply to this email directly or view it on GitHub<https://github.com/tomchristie/django-rest-framework/pull/571/files#r2648461>.
>
>