方法(Methods)
模型方法也是非常强大的工具,可以建立在属性之上。
🔖 方法 vs 属性
- 属性:不接受参数(除了 self),像字段一样访问
- 方法:可以接受参数,需要括号调用
让我们看一个带有 is_within(self, x) 方法的示例:
from django.core.exceptions import ValidationError
from django.utils import timezone
class Course(BaseModel):
name = models.CharField(unique=True, max_length=255)
start_date = models.DateField()
end_date = models.DateField()
def clean(self):
if self.start_date >= self.end_date:
raise ValidationError("End date cannot be before start date")
@property
def has_started(self) -> bool:
now = timezone.now()
return self.start_date <= now.date()
@property
def has_finished(self) -> bool:
now = timezone.now()
return self.end_date <= now.date()
def is_within(self, x: date) -> bool:
return self.start_date <= x <= self.end_date
📝 代码说明
is_within不是属性,因为它需要一个参数。所以它是一个方法。