根据Django模型中的一个条件,根据需要创建一个模型字段

2024-03-29 02:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python(3.6)和Django(2.0)开发一个项目,在这个项目中,我需要根据父模型类中字段的条件,在子模型中创建一个字段。在

如果服务是多个,则需要路由配置字段,否则不需要填写。在

这是我的代码模型.py

From models.py:

services = (
    ('Single', 'Single'),
    ('Multiple', 'Multiple'),
)


class DeploymentOnUserModel(models.Model):
    deployment_name = models.CharField(max_length=256, )
    credentials = models.TextField(blank=False)
    project_name = models.CharField(max_length=150, blank=False)
    project_id = models.CharField(max_length=150, blank=True)
    cluster_name = models.CharField(max_length=256, blank=False)
    zone_region = models.CharField(max_length=150, blank=False)
    services = models.CharField(max_length=150, choices=services)
    configuration = models.TextField(blank=True)
    routing = models.TextField(blank=True)

    def save(self, **kwargs):
        if self.services == 'Multiple' and not self.routing and not self.configuration:
            raise ValidationError("You must have to provide routing for multiple services deployment.")
        super().save(**kwargs)

From serializers.py:

^{pr2}$

From apiview.py:

class DeploymentsList(generics.ListCreateAPIView):
    queryset = DeploymentOnUserModel.objects.all()
    serializer_class = DeploymentOnUserSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        serializer = DeploymentOnUserSerializer(data=self.request.data)
        validation = serializer.is_valid()
        if validation is True:
            perform_deployment(self.request.data)
            self.create(request=self.request)
        else:
            return Response('You haven\' passed the correct data ')
        return Response(serializer.data)

Post payload:

{
  "deployment_name": "first_deployment",
  "credentials":{
  "type": "service_account",
  "project_id": "project_id",
  "private_key_id": "private_key_id",
  "private_key": "-----BEGIN PRIVATE KEY",
  "client_email": "client_email",
  "client_id": "client_id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "client_x509_cert_url"
},
  "project_name": "project_name",
  "project_id": "project_id",
  "cluster_name": "numpy",
  "zone_region": "europe-west1-d",
  "services": "Single",
  "configuration": "",
  "routing": ""
}

Update: Now I have implemented apiview and serializers for these models. When I submit a post request with the services=Single without the values for configuration & routing it returns You haven't passed the correct data.

这意味着save方法不起作用。 请帮帮我!在

提前谢谢!在


Tags: nameselfprojectclientiddatamodelsrequest
1条回答
网友
1楼 · 发布于 2024-03-29 02:18:56

除了我的评论之外,您还可以重写AwdModel模型的save()方法。在

from django.core.exceptions import ValidationError


class AwdModel(UserAccountModel):
    source_zip = models.FileField(upload_to='media/awdSource/', name='awd_source')
    routing = models.TextField(name='routing', null=True)

    def save(self, **kwargs):
        if not self.id and self.services == 'Multiple' and not self.routing:
            raise ValidationError("error message")
        super().save(**kwargs)

如果是新实例,self.id将是null或类似,因此只有在创建实例时才会进行验证检查

Update-1使用此有效负载发布

^{pr2}$

更新-2 对序列化程序尝试此操作,

class DeploymentOnUserSerializer(serializers.ModelSerializer):
    credentials = serializers.JSONField()
    class Meta:
        model = DeploymentOnUserModel
        fields = '__all__'

相关问题 更多 >