如何使用布尔值从 class 更改 Django 模型

How to change Django model from class using boolean

我的 models.py

中有位置 class
class Location(models.Model):
    ...
    orderplaced = models.DateTimeField(auto_now_add=True, blank=True)
    ordersent = models.BooleanField(default=False)
    order_sent_time = models.DateTimeField(auto_now=True, blank=True)

admin.py

class locationAdmin(admin.ModelAdmin):
    readonly_fields = ["orderplaced", "order_sent_time"]

admin.site.register(Location, locationAdmin)

如何让布尔 ordersent 控制 if order_sent_time 是否为空

我试过使用

if ordersent:
    order_sent_time = models.DateTimeField(auto_now=True, blank=True)
else:
    order_sent_time = models.DateTimeField(null=True, blank=True)

如何让布尔值影响 order_sent_time?

要在 Django 中动态设置对象的某些值,您可以覆盖 save() 方法:

# Assume that (USE_TZ=True) in settings file
from django.utils import timezone

class Location(models.Model):
    ...
    orderplaced = models.DateTimeField(auto_now_add=True, blank=True)
    ordersent = models.BooleanField(default=False)
    order_sent_time = models.DateTimeField(null=True, blank=True)

    def save(self, *args, **kwargs):
        # If ordersent is True then set order_sent_time to now
        if ordersent:
            self.order_sent_time = timezone.now()
        super(Location, self).save(*args, **kwargs) 
        return self

注意:每次创建或编辑 Location 对象时,它都会检查 ordersent 变量是否为 True,然后 order_sent_time设置为运行日期。否则它将是 none.