[Answered ]-"<Post:>" needs to have a value for field "id" before this many-to-many relationship can be used

1👍

You need to make a super().save(*args, **kwargs) call. Furthermore using a constant will not work: this will assign the time when you started the server, not the current time, so:

from django.utils.timezone import now

class Post(models.Model):
    # …

    def save(self, *args, **kwargs):
        if not self.id:
            self.created_at = now()
        self.updated_at = now()
        super().save(*args, **kwargs)

You furthermore do not need to specify logic to update the created_at and updated_at field, you can work with auto_now_add=True [Django-doc] and auto_now=True [Django-doc]:

class Post(models.Model):
    # …
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    # …

    class Meta:
        ordering = ['-created_at']

    # no save override

    def __str__(self):
        return self.title

Leave a comment