使用django rest框架的复合形式

时间:2013-07-09 05:46:17

标签: django-rest-framework

-------------模型

class Contact(models.Model):
    email = models.EmailField()


class Client(models.Model):
    name = models.CharField(max_length=256)
    contact = models.ForeignKey('Contact')


class Vendor(models.Model):
    name = models.CharField(max_length=256)
    contact = models.ForeignKey('Contact')

-------------模型序列化器

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact


class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client


class VendorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Vendor

“客户表格”应包含以下字段: 客户模型的所有领域& 联系模型的所有领域

使用单个'ClientSerializer'可以实现吗?

1 个答案:

答案 0 :(得分:1)

假设Client Form您正在讨论API端点的序列化程序(我正确理解您的问题):

由于ClientVendor已链接到Contact,因此您可以将这些添加为子结构。

class ContactSerializer(serializers.ModelSerializer):
    clients = ClientSerializer(many=True)
    vendors = VendorSerializer(many=True)

    class Meta:
        model = Contact

请参阅documentation on nested relationships