7
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.
1
Case 1:
Don’t do it like that, have a different table for telephone numbers and have a ForeignKey
from the Person (I’m assuming it’s a person) to the the telephone number. If you have more than one telephone number per person, do it the other way around, otherwise consider using a OneToOne
.
Obviously you’ll want the ForeignKey
to be nullable. That way, the only way to have a telephone number is if the person provided one.
Case 2:
I don’t understand your database design here, so I can’t answer. You’ll have to explain more – why do you need a ManyToMany
here?
- [Django]-Getting 400's from aws ELB hostcheck to work with django ALLOWED_HOSTS in aws ECS under awsvpc networking mode?
- [Django]-Python Webshop for Retailers / Distributors
- [Django]-Django app under uwsgi failing to start when using postgresql database
- [Django]-I can't install 'pip install pil' in Osx