Issue
I have the following code. The expect outcome would be:
- If the event does not exist, then the admin form shows only created_at time, the updated_at field is empty.
- If the event exists: a. if there is no updated_at, the field would be filled with time now. b. if updated_at exists, the field time should be updated.
My code does not work, how should I change it? Thank you.
from django.db import models
from django.utils.timezone import now
import uuid
class Venue (models.Model):
class Types(models.TextChoices):
LPN='LPN',
RN ='RN'
type = models.CharField(
max_length=3,
choices=Types.choices,
default=Types.RN
)
venue_id= models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(default=now, editable=True,null=True, blank=True)
if venue_id is True:
updated_at = models.DateTimeField(default=now, editable=True,null=True, blank=True)
updated_at.update()
else:
updated_at = models.DateTimeField(default=None, editable=True,null=True, blank=True)
place_text=models.CharField(max_length=200)
date = models.DateField ('Date')
start_time = models.DateTimeField ('start time')
finish_time= models.DateTimeField ('finish time')
details= models.CharField (max_length=500)
def _str_(self):
return self.venue_text
please refer to the attached screenshot.
Solution
Logic like this should be done via signal.
https://docs.djangoproject.com/en/4.0/ref/signals/#post-save
If you specify logic on model like this it does not register changes.
Redefine your models with all field you want it to have, if you want
update_at field to be null upon creation, until it actually gets
updated go with default=None, otherwise you can use auto_now.
If you want certain action to happen after you edit any field or so,
go with signals.
Answered By - David Roučka
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.