I am creating a Django app and this questions comes to hit me again (I've already run into it but I resolved it in a way I don't think is correct).
So I have these models:
def Person(models.Model):
name = models.CharField(max_length=30)
status = models.ManyToManyField(Status)
def Status(models.Model):
name = models.CharField(max_length=30)
Any person may have up to 3 status (or none). And this was supposed to be a string array containing only a few possible status. e.g. happy, lucky, strong.
However a CharField with choices would not be possible here, as one person may feel happy and strong at the same time.
Is my current approach the best one possible?
You will need to validate the statuses count for each person in the clean
method.
from django.db import models
from django.core.exceptions import ValidationError
class Status(models.Model):
name = models.CharField(max_length=30)
class Person(models.Model):
name = models.CharField(max_length=30)
status = models.ManyToManyField(Status)
def clean(self):
# check person status count
if self.status.all().count() > 3:
raise ValidationError("Person can not have more than 3 statuses")
Update
Since it's a ManyToMany
relationship, you will never get this validated during the creation of the object, unless you have a separate form for adding statuses for persons.
If you have statuses field in the same form of person creation, then this check MUST be in the form.
class PersonForm(forms.ModelForm):
class Meta:
model = Person
def clean(self):
statuses = self.cleaned_data.get('status')
if status.count() > 3:
raise ValidationError("Person can not have more than 3 statuses")
Why this method
This design of models will allow you to have many different ways of querying. such as get people who are happy!
or count of people who are sad
and finally get people with similar statuses