Home > database >  How to serialize a through relationship in django
How to serialize a through relationship in django

Time:06-04

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.

CodePudding user response:

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

  • Related