i have Datefield in my model where it should save when created and updated what should be the attributes inside?
models.py
class Mymodel(models.Model):
edited = models.DateField(*what should be the attributes here*)
CodePudding user response:
Add two attributes, One is created_at and another is edited_at
created_at = models.DateField(auto_now_add=True)
edited_at = models.DateField(auto_now=True)
auto_now -> Automatically set the field to now every time the object is saved.
auto_now_add -> Automatically set the field to now when the object is first created.
for details see the reference
CodePudding user response:
You can read this.
class Mymodel(models.Model):
edited = models.DateField(auto_now_add=True)
auto_now_add
attribute's True
value will add current date whenever you create that object for MyModel
and then let's see an example:
in your views.py
data = MyModel.objects.get(id=some_id)
data.some_field1 = 'some-value'
data.some_field2 = 'some-value'
data.edited = datetime.date.today()
data.save()
You have to just do this
CodePudding user response:
We can use custom save method as auto_now or auto_now_add will not show in admin panel. Below is the example for the same By this approach we can actually track both when it is created and when it is updated.
from django.utils import timezone
class User(models.Model):
created = models.DateTimeField(editable=False)
edited = models.DateTimeField()
def save(self, *args, **kwargs):
if not self.id:
self.created = timezone.now()
self.edited = timezone.now()
return super(User, self).save(*args, **kwargs)