问题
I have a model:
class MyModel(models.Model):
user = models.ForeignKey(User)
week = models.DateField()
My app is being built around "weeks ending on a Saturday", so I would like the week
field to only accept days that are a Saturday.
I'd like this validation to happen in the Model
rather than in a Form
, as I'm going to have data input without a Form
in certain circumstances.
I understand that overriding the model's save()
method to add a full_clean()
is probably the way to go, but I'm confused about what the best practice is here.
What's the DRYest way?
回答1:
I would go with providing a validator, especially if you need a clean DB when inputting data without a form.
If the input is a datetime.date
, you can just use mydate.weekday()
to get its day of week. It should be '5' for Saturday.
Something like:
def validate_saturday(value):
if not value.week.weekday == 5:
raise ValidationError("Date should be a Saturday.")
An alternative might be to specify the week number in your models instead of a DateField.
回答2:
You can specify a validator on the field
week = models.DateField(validators=[validate_sat])
def validate_sat(value):
if value is not a saturday:
raise ValidationError('%s isn't a saturday' % value)
I've left out the actual logic to work out what day of a week the date is but that shouldn't be too difficult
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form
Now since you say you may not use forms in all instances of saving, you may want to use a pre_save signal that will do the validation, you can always raise the validation error in this if it isn't a valid value.
If at all possible, it might be worth trying to consolidate your model updating methods to update from forms.
来源:https://stackoverflow.com/questions/35033758/what-is-the-best-practice-to-validate-a-django-datefield-at-the-model-level-as-p