gpt4 book ai didi

Django:只能填写两个字段之一

转载 作者:行者123 更新时间:2023-12-02 08:38:16 25 4
gpt4 key购买 nike

我有这个模型:

class Journals(models.Model):
jid = models.AutoField(primary_key=True)
code = models.CharField("Code", max_length=50)
name = models.CharField("Name", max_length=2000)
publisher = models.CharField("Publisher", max_length=2000)
price_euro = models.CharField("Euro", max_length=2000)
price_dollars = models.CharField("Dollars", max_length=2000)

有没有办法让人们填写 price_europrice_dollars

我确实知道解决问题的最佳方法是只有一个字段和另一个指定货币的表,但我有限制,无法修改数据库。

谢谢!

最佳答案

Since Django 2.2 database constraints can be used.这意味着,除了常规模型级验证(一直有效且 has been suggested by Tom )之外,您现在可以确保无效数据根本无法进入数据库。

# models.py 
from django.db import models
from django.db.models import Q

class Journals(models.Model):
# [...]

def clean(self):
"""Ensure that only one of `price_euro` and `price_dollars` can be set."""
if self.price_euro and self.price_dollars:
raise ValidationError("Only one price field can be set.")


class Meta:
constraints = [
models.CheckConstraint(
check=(
Q(price_euro__isnull=False) &
Q(price_dollars__isnull=True)
) | (
Q(price_euro__isnull=True) &
Q(price_dollars__isnull=False)
),
name='only_one_price',
)
]

确保在更改 Meta.constraints 后创建并应用迁移。 Documentation on Meta.constraints is available here.

关于Django:只能填写两个字段之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2723826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com