3

- - - - - - -楷模

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”吗?

4

1 回答 1

1

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

由于ClientVendor链接到Contact,您可以将它们添加为子结构。

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

    class Meta:
        model = Contact

请参阅有关嵌套关系的文档

于 2014-03-13T08:18:58.177 回答