我想将这些字段添加到我的存储模型中,但我想包含这样的逻辑:如果我们假设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,
)这样,您的逻辑仍然连接到模型,并且可以在代码的多个位置重用实例创建。
https://stackoverflow.com/questions/70421916
复制相似问题