Home > Enterprise >  How to change Django model from class using boolean
How to change Django model from class using boolean

Time:10-28

I have the location class in my models.py

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)

How do I make it so that the boolean ordersent controls the if order_sent_time is blank or not

enter image description here

I tried using

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

How can I get the boolean to affect order_sent_time?

CodePudding user response:

To dynamically set some value of an object in Django, you can override the save() method :

# 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

Note : Each time you will create or edit a Location object, it will check if the ordersent variable is True, then order_sent_time will be set to the runtime date. Else it's will be none.

  • Related