How can I have field dependency?
Case 1: If boolean field call_me is set, then telephone must be set, else it should be blank
Case 2: If many to many field category (with values sale, rent) has one of the values as sale, then price_sale must be set, else it should be blank
For Case 1, you can validate that easily in the model's clean method:
from django.core.exceptions import ValidationError
class MyModel(models.Model):
...
def clean(self):
if self.call_me and not self.telephone.strip():
raise ValidationError('Telephone is required')
For Case 2, M2M relationships are not added until after the model is saved, so using clean on your model won't work in this scenario. However, you can do this from the clean method of any ModelForm you use to edit this, be it in the admin or your own view.
However, having category as a M2M when the only possible values are "sale" and "rent", is poor design. Even then, "sale" and "rent" are mutually exclusive, so an M2M is inappropriate anyways (your model won't be experiencing both a "sale" and a "rent" at the same time ever).
As a result, it would be a better idea to have category be a CharField with choices consisting of "sale" and "rent". If you do it that way, you can then use your model's clean method in the same way as Case 1 for this as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With