Issue
I am creating a Django model where:
expirationTimeStamp field's default value is based on creationTimeStamp
isLive boolean field value is based on expirationTimeStamp
I have written the following functions expirationTimeCalculation and postLiveStatus and assigned them as default values to the fields but I am getting error. I have also tried to assign to respective fields through property(function) yet I am still getting error.
One of the functionality that I need to implement is that user can send custom expirationTimeStamp as well that would override default value, therefore, I believe property(function) assignment is not ideal for expirationTimeStamp field.
Is there any other way that I can go about to set the expirationTimeStamp field value based on creationTimeStamp field?
Any feedback is appreciated!
class Posts(models.Model):
def expirationTimeCalculation(self):
EXPIRATION_DURATION = 86400 #time in seconds
expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION)
return expirationTime
def postLiveStatus(self):
return (self.expirationTimestamp > timezone.now)
message = models.TextField()
creationTimestamp = models.DateTimeField(default=timezone.now)
expirationTimestamp = models.DateTimeField(default=expirationTimeCalculation)
isLive = models.BooleanField(default=postLiveStatus)
Solution
Similar answered question. I am attaching the official documentation as well as the link to the answered question.
Models certainly do have a "self"! It's just that you're trying to define an attribute of a model class as being dependent upon a model instance; that's not possible, as the instance does not (and cannot) exist before your define the class and its attributes.
To get the effect you want, override the save() method of the model class. Make any changes you want to the instance necessary, then call the superclass's method to do the actual saving. Here's a quick example.
def save(self, *args, **kwargs): if not self.subject_init: self.subject_init = self.subject_initials() super(Subject, self).save(*args, **kwargs)
Model Overriding Documentation
Django Model Field Default Based Off Another Field
Answered By - SANGEETH SUBRAMONIAM
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.