Jamgreen
Jamgreen

Reputation: 11069

Wiki like Django models

I am trying to make a wiki like page in Django.

I have two models Article and ArticleRevision.

If I want to retrieve the most current revision I think I need an OneToOneField in Article refering to ArticleRevision. But if I want to see the revision history of an article I also need a ForeignKey from ArticleRevision refering to Article.

This is probably the right approach but isn't it a bit overkill to have multiple foreign keys? I could do it with only a ForeignKey(to=Article) from ArticleRevision and getting the latest revision from Article with articlerevision_set.latest(). But if I am making a roll-back to an early revision it will cause troubles. Then I could use a BooleanField in ArticleRevision to tell if it's the most current revision.

Does anyone have any thoughts about this? I really want to do it the best and most efficient way.

Upvotes: 1

Views: 138

Answers (2)

AlvaroAV
AlvaroAV

Reputation: 10563

What about a new field in ArticleRevision like created, something like:

class ArticleRevision(models.Model):
    # Your fields
    created = models.DateTimeField(auto_now_add=True, verbose_name=_(u'Creation Date'))

auto_now_add=True <-- This means the field will be autogenerated when an object is created


then you can add a new method in your Article model like this:

class Article(models.Model):
    # Your fields...
    # I will assume you have a foreign key from ArticleReview to Article

    def get_latest_revision(self):
        if self.articlerevision_set.count() > 0:  # If there is revision
            last_revision = self.articlerevision_set.order_by('-created')[0]
            return last_revision
        else:
            return None

Remember: To do this you need a ForeignKey from ArticleRevision to Article

Upvotes: 0

codingjoe
codingjoe

Reputation: 1257

You should take a look at django-revisions. It allows you to do just what you need, without reimplementing everything.

Upvotes: 1

Related Questions