开发者

Django passing a model instance to slightly different model

I'm writing an django app for a project where everybody can change articles but the changes that users commit have to be viewed by someone before they 开发者_开发技巧go online. So you see it is a bit like the system used by wikipedia.

class Content(models.Model):
    tp = models.DateTimeField(auto_now_add=True)
    topic = models.CharField(max_length=60)
    content = models.TextField()
    slug = models.SlugField(max_length=80)

class ChangeSet(Content):
    content = models.ForeignKey('Content')

those are my models. ChangeSet just inherits the Content and it has a ForeignKey to the original content.

my question is how do I save my ChangeSet?

def content(request, content_slug):
    content = get_object_or_404(Content, slug=content_slug)
    if request.method == 'POST':
        new_content = ContentModelForm(request.POST, instance=content)

        new_content = new_content.save(commit=False)

        changeset = ChangeSet(content=content)

can I somehow pass the ChangeSet the content instance? Does Django recognize that those two models are the same except for the fk? Or do I have to manually add every field like:

changeset.topic = new_content.topic

Edit #1

It doesn't look like it's a big deal to just write 'changeset.topic = new_content.topic' but I shortened my real Content model so you guys won't have to read all the stuff that is irrelevant for solving this problem.

Edit #2

To generalize the question a bit more. What is the best way saving Changesets? Making a new model for the changeset like I did or should I just add a ForeignKey with a reference to itself to my Content model?


The way you have your models coded, I don't think it's going to work like you're expecting. In this case ChangeSet inherits from Content. The way Django implements this is by create a OneToOneField that connects ChangeSet with Content. This means 2 things for your application:

  1. Having the ForeignKey is pointless as that's like having an FK to yourself (and there's already a OneToOne behind the scenes anyways)
  2. ChangeSet is always going to point to the most recent instance of Content. There's nothing in this model setup that is going to save a copy of changes.

Probably the best method I've seen to achieve this (used by django-reversion) is to take Content, serialized it, then save the Content Id and Content Type to a model. You can than access it like ChangeSet.original.{tp/topic/etc.}.

Have a look at it's model code here: models.py. The equivalent to your ChangeSet would be the Version model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜