Search code examples
jquerysqldjangodjango-rest-frameworkdjango-serializer

How to serialize a through relationship in django


I have my models here like this

class individual(models.Model):
    individualName = models.CharField(*args)

class family(models.Model):
    familyName = models.CharField(*args)
    individuals = models.ManyToManyField(individual, through='individualthroughfamily')

class individualthroughfamily(OrderedModel):
    family = models.ForeignKey(family)
    individual = models.Foreignkey(individual)
    order_with_respect_to = 'family'

    class Meta:
        ordering = ['family', 'order']

Here "OrderedModel" is an open-source app available for Django.

So, now I want to serialize the family model such that I can get nested individuals according to the order defined in the third class. But, I can't find my way, and it is getting too confusing. Happy to answer any queries.


Solution

  • You can use a SerializerMethodField, and order the individuals queryset using the through relation:

    class FamilySerializer(serializers.ModelSerializer)
        class Meta:
            model = Family
            fields = [
                'family_name',
                'individuals'
            ]
        
        individuals = serializers.SerializerMethodField()
    
        def get_individuals(self, obj):
            individuals = obj.individuals.order_by('individualthroughfamily__order')
            return IndividualSerializer(individuals, many=True).data