我会简单地添加一个状态,但判断是否使用了结束时间戳.通过定义一个字段status
,你引入了data duplication,你指定了同样的东西twice.
您可能还应该combine日期和时间,因为时间戳不仅仅是日期和时间,例如daylight saving time.
from django.conf import settings
class Auction(models.Model):
auction_id = models.AutoField(primary_key=True)
crop = models.ForeignKey(Crop, on_delete=models.CASCADE)
image = models.ImageField(upload_to='crop-image')
farmer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
limit_choices_to={'user_type': 'farmer'},
)
creation_time = models.DateTimeField(auto_now_add=True)
end_timestamp = models.DateTimeField()
# no status
qty = models.IntegerField()
unit = models.CharField(
max_length=10,
choices=[
('kg', 'Kilograms'),
('tonne', 'Metric Tons'),
('bushel', 'Bushels'),
('crate', 'Crates'),
],
)
hammer_price = models.IntegerField()
description = models.CharField(max_length=200)
payment = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'Auctions'
def __str__(self):
return self.crop.title
例如,我们可以获得所有仍然活跃的Auction
:
from django.db.models.functions import Now
Auction.objects.filter(end_timestamp__gte=Now())
现在,我们以passive种方式确定状态,这通常比主动改变状态的进程更可靠.
我们可以通过设置db_index=True
[Django-doc]来提高性能.
Note:通常使用settings.AUTH_USER_MODEL
[Django-doc]来引用用户模型比直接使用User
model [Django-doc]更好.更多信息可以看referencing the User
model section of the documentation [Django-doc].