如何在Django中自动更改模型字段 [英] How to automatically change model fields in django
问题描述
我有一个模型,我想知道是否可以设置一个条件来触发模型字段中的更改。例如,我有一个模型
I have a model and I want to know if it is possible to set a condition that triggers a change in the model field. For example, I have a model
class BillboardTracker(models.Model):
client_name = models.CharField(max_length=400)
entry_date = models.DateTimeField(default=datetime.now)
duration = models.PositiveIntegerField()
expiry_date = models.DateField()
is_expired = models.BooleanField(default=False)
我想知道模型中是否可以有一个函数当到期日期到期时,使is_expired等于True。我试过了
I want to know if it is possible to have a function in the model that makes is_expired equals to True when the expiry date is up. I tried this
def expire(self):
if datetime.now == self.expiry_date:
self.is_expired = True
,但它不起作用。
推荐答案
使用@属性
这里最简单的事情是根本没有过期字段!不需要您需要的是财产。
Use a @property
The simplest thing here is not to have an is expired field at all! It's not needed. What you need is a property.
class BillboardTracker(models.Model):
client_name = models.CharField(max_length=400)
entry_date = models.DateTimeField(default=datetime.now)
duration = models.PositiveIntegerField()
expiry_date = models.DateField()
@property
def is_expired(self):
if datetime.now > self.expiry_date:
return True
return False
记住,您不如果数据库中的某个字段与另一个字段(通过简单的计算)相同,则该字段中没有数据库。这样会自动消除您不必将项目标记为已过期的烦恼。
Remember, you don't have a field in a database, if that field is the same as another field with a simple calculation. This automatically eliminates your head ache of having to flag items as expired.
如果您要查找对象是否已过期。
If you want to find out if an object has expired.
if instance.is_expired == True:
print 'yes, that ones gone'
过滤
如果要检索整套对象,已过期
Filtering
If you wanted to retrieve a whole set of objects that have expired
BillboardTracker.objects.filter(expiry_date__le=datetime.now())
这就是为什么我提到您不需要存储易于计算的字段的原因。
This is why I mentioned that you don't need to store a field that can be easily calculated.
在大多数RDBMS中,布尔字段(例如is_expired列)无法有效地建立索引。因此,这实际上意味着,只要您在expiry_date字段上创建索引,上述查询就会比对该布尔字段的查询要快。
In most RDBMS a boolean field (such as your is_expired column) cannot be indexed effectively. So that actually means the above query will be faster than a query on that boolean field provided you create an index on the expiry_date field.
这篇关于如何在Django中自动更改模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!