如何在 Django 中序列化直通关系

How to serialize a through relationship in django

我这里有这样的模型

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']

此处“OrderedModel”是一个可用于 Django 的开源应用程序。

所以,现在我想序列化家庭模型,这样我就可以根据第三个class中定义的顺序获得嵌套的个体。但是,我找不到我的路,而且它变得太混乱了。很高兴回答任何问题。

您可以使用 SerializerMethodField,并使用直通关系对 individuals 查询集进行排序:

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