1

In my blog I decided to allow users to edit posts (I am using Django), but I am not sure what is the right implementation for my models to do that. Is a good idea to use multi-table inheritance as my code below? I also want to keep track of all the posts, originals as the every new edited as well.

class Post(models.Model):
    title = models.CharField(max_length=500)
    text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return "%s %s by %s" % (self.title, self.creation_date, self.user)

class Edit(Post):
    edited_date = models.DateTimeField(auto_now_add=True)
    editor = models.OneToOneField(User)

    def __unicode__(self):
        return "%s edited by %s" % (self.convention, self.login)
Pompeyo
  • 1,459
  • 3
  • 18
  • 42

1 Answers1

1

What you need is version control. There are apps that can implement it. But if you want to do it yourself, then your Edit model must have a reference to the Post models. And must point to a specific post corresponding to the author of that edit. That necessarily means you have to create a Post instance every time a post is saved and you must point to that new instance from the Edit instance.

Something like this, but may need more work -

class Post(models.Model):
    title = models.CharField(max_length=500)
    text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    edited_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User)

    def __unicode__(self):
        return "%s at %s by %s" % (self.title, self.creation_date, self.author.first_name)

class Edit(models.Model):
    creation_date = models.DateTimeField(auto_now_add=True)
    editor = models.ForeignKey(User)
    post = models.ForeignKey(Post)

    def __unicode__(self):
        return "%s edited by %s" % (self.post.title, self.editor.first_name)
Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
  • Thanks for your answer Bibhas, using your suggestion means, that I have to re-create some fields inside the Edit class (title, text). isn't? For Example, this may look like that: Is it right? `class Edit(models.Model): creation_date = models.DateTimeField(auto_now_add=True) editor = models.ForeignKey(User) post = models.ForeignKey(Post) title = models.TextField() text = models.CharField(max_length=500) def __unicode__(self): return "%s edited by %s" % (self.post.title, self.editor.first_name)` – Pompeyo Sep 11 '13 at 17:58
  • No. You don't have to. Every edit points to the corresponding post object which already has those fields. – Bibhas Debnath Sep 11 '13 at 19:39