【问题标题】:Make a model field as required on the base of a condition in Django Models根据Django Models中的条件制作模型字段
【发布时间】:2018-11-28 03:08:48
【问题描述】:

我正在使用 Python(3.6)Django(2.0) 开展一个项目,在该项目中,我需要在子模型的基础上创建一个字段父模型类中字段的条件。

如果 service 是多个,则 routingconfiguration 字段将是必填项,否则无需填写。

这是我在 models.py 中的代码

来自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)

来自 serializers.py:

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

来自 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)

发布有效载荷:

{
  "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": ""
}

更新:现在我已经为这些模型实现了 apiview 和序列化程序。当我使用services=Single 提交没有configuration & routing 值的发布请求时,它返回You haven't passed the correct data.

这意味着保存方法不起作用。 请帮帮我!

提前致谢!

【问题讨论】:

标签: python django python-3.x django-models django-2.0


【解决方案1】:

除了我的评论,你可以覆盖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 使用此负载进行 POST

{
  "deployment_name": "first_deployment",
  "credentials":{"test_key":"test_value"},
  "project_name": "project_name",
  "project_id": "project_id",
  "cluster_name": "numpy",
  "zone_region": "europe-west1-d",
  "services": "Single",
  "configuration": "",
  "routing": ""
}

更新-2 为您的序列化程序试试这个,

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

【讨论】:

  • 嗨@JerinPeterGeorge,我已经更新了问题,请看一下!
  • 平均后输入对象?
  • 你传递给视图的 JSON 数据
  • 同时添加 print(serializer.errors) 的输出。 (在validation = serializer.is_valid()这个语句之后添加那个print())
  • serializer.error 打印 {'credentials': ['Not a valid string.']}
猜你喜欢
  • 2022-10-24
  • 2022-07-23
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2015-02-14
  • 2016-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多