在Django Rest Framework中有一个下拉列表的多对多模型?

时间:2018-04-08 20:10:16

标签: python django django-rest-framework

我正在尝试使用其间的模型创建多对多关系,我有一个客户端模型和一个区域模型,每个客户端可以访问不同的区域,每个区域可能有多个客户端。

因此我创建了一个名为Access Permission的模型,它存储了所述关系,我希望在post表单中显示一个显示现有客户端和区域的下拉选择器,或者询问现有对象的Id,而不是显示创建新表单的表单。

这些是我的模特:

class Zone(models.Model):
    name = models.TextField()
    created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '%s' % (self.name)


class Client(models.Model):
    name = models.TextField()
    birthDate = models.DateField()
    created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return '%s' % (self.name)


class AccessPermission(models.Model):
    idClient = models.ForeignKey(Client, on_delete=models.CASCADE, null=False)
    idZone = models.ForeignKey(Zone, on_delete=models.CASCADE, null=False)

这些是我目前的序列化器:

class ZoneSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Zone
        fields = ('name',)


class ClientSerializer(serializers.HyperlinkedModelSerializer):
    zones = ZonesSerializer(source='accesspermission_set', many=True, read_only=True)

    class Meta:
        model = Client
        fields = ('name', 'birthDate',  'zones')


class AccessPermissionSerializer(serializers.ManyRelatedField):
    idClient = ClientSerializer(many=False)
    idZone = ZoneSerializer(many=False)

    class Meta:
        model = AccessPermission
        fields = ('idClient', 'idZone')

有没有办法要求现有对象的ID,或显示现有对象,而不是创建新对象的字段?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

  

模型

class AccessPermission(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False)
    zone = models.ForeignKey(Zone, on_delete=models.CASCADE, null=False)
  

串行

class AccessPermissionSerializer(serializers.ManyRelatedField):
    id = serializers.IntegerField(read_only=True)
    client_id = serializers.PrimaryKeyRelatedField(
        queryset=Client.objects.all(), source='client', allow_null=False, required=True
    )
    zone_id = serializers.PrimaryKeyRelatedField(
        queryset=Zone.objects.all(), source='zone', allow_null=False, required=True
    )

    class Meta:
        model = AccessPermission
        fields = (
            'id', 'client_id', 'zone_id'
        )