我想将这些字段添加到我的存储模型中,但我想包含这样的逻辑:如果我们假设WooCoomerce被选为StoreType,我希望不需要Access_Token。此外,当我选择Shopify/Shopper时,我希望不需要Consumer_key和Consumer_secret。你知道怎么绕过它吗?
StoreType = models.CharField(blank=True, choices=Storetypes.choices, max_length=12)
Api_Url = models.CharField(blank=True)
Access_Key = models.CharField(blank=True, max_length=100)
Consumer_Key = models.CharField(blank=True, max_length=100)
Consumer_Secret = models.CharField(blank=True, max_length=100)发布于 2021-12-20 13:23:40
您不能在数据库层上创建这种逻辑。在这种情况下,您可以将此逻辑移动到模型的类方法中,以满足干模式。还将模型中的字段设置为可空。
差不多是这样的:
class YourClass(models.Model):
store_type = models.CharField(blank=True, choices=Storetypes.choices, max_length=12)
api_url = models.CharField(blank=True,)
access_key = models.CharField(blank=True, max_length=100, null=True)
consumer_key = models.CharField(blank=True, max_length=100, null=True)
consumer_secret = models.CharField(blank=True, max_length=100, null=True)
@classmethod
def save_woo_commerce(cls, api_url, consumer_key, consumer_secret):
return YourClass.objects.create(
store_type="woo_commerce",
api_url=api_url,
consumer_key=consumer_key,
consumer_secret=consumer_secret
)
@classmethod
def save_shopify(cls, api_url, access_key):
return YourClass.objects.create(
store_type="shopify",
access_key=access_key,
api_url=api_url,
)这样,您的逻辑仍然连接到模型,并且可以在代码的多个位置重用实例创建。
发布于 2021-12-20 13:24:13
在某种程度上,这些字段将成为输入。
如果它们是通过表单出现的,那么就需要使用clean方法为无效的组合生成错误,或者在视图级别进行检查。我发现在基于类的视图(基于FormView)中经常使用的模式如下所示。关键点:将有效表单转换为无效表单的form.add_error,以及向用户展示需要修复的内容的return self.form_invalid(form)。
def form_valid( self, form)
store_type = form.Cleaned_data['store_type']
api_url = form.cleaned_data[' ... ']
...
# now, further checks
...
errors = False
if store_type == SHOPIFY or store_type == SHOPPER:
# consumer_key and consumer secret not required
consumer_key = consumer_secret = ''
# but presumably, api_url and access_key are mandatory
if api_url == '':
# get human representation of store_type
human_store_type = ...
form.add_error('api_url', f'API Url is required whenever store type is "{human_store_type}"' )
errors = True
if access_key == '':
... # similar, but add error to access_Key field
# maybe validate that the api_url and access_key actually work
# and add an error if they don't work together?
if not check_valid( api_url, access_key):
errors = True
form.add_error( None, 'api_url and access_key do not work with each other') # non-field error
if errors:
return self.form_invalid( form)
elif store_type == ...
...
# OK we have a completely valid set of inputs
# get the object (if its a ModelForm)
store = form.save( commit = False)
store.api_url = api_url
... # and the other fields we extra-validated
store.save()
return redirect( ...)如果任何强制字段为空,则可以对对象上的save方法进行子类化,以导致异常,但这可能会带来比其价值更大的麻烦。如果有一个或几个视图可以设置这些字段,那么检查那里。有时,保存一个不完整的对象甚至是有用的:给它一个布尔is_complete字段。例如,人工主管可能需要授权添加一个新的商店。
https://stackoverflow.com/questions/70421916
复制相似问题