I want to add these fields to my Store Model, but i wanna include logic that if Let’s say WooCoomerce was chosen as a StoreType, i want Access_Token not to be Required. Also when i Choose either Shopify/Shopper i want Consumer_key and Consumer_secret not to be required. Do you have any idea how to get around that?
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)
2
Answers
You can’t make this type of logic on database layer. For this case you can move this logic to a classmathod of the model to satisfy the dry-pattern. Also set the fields to nullable in your model.
Something like so:
With that your logic is still connected to the model and you can reuse instance creation on multiple places of your code.
At some point those fields are going to be inputs.
If they come in through a form, it’s a matter of using a
clean
method that generates errors for invalid combinations, or checking at the view level. A pattern I have found myself using quite often with class-based views (based on FormView) is like the following. Key points:form.add_error
to convert a valid form into an invalid one, andreturn self.form_invalid(form)
to show the user what needs to be fixed.It’s possible to subclass the
save
method on your object to cause an exception if any mandatory fields are blank, but this can be more trouble than its worth. If there is one or few views through which these fields can be set, then check there. Sometimes, it’s even useful to save an incomplete object: give it a Boolean is_complete field. For example, it may be necessary for a human supervisor to authorize the addition of a new store.