kgodey
kgodey

Reputation: 43

Copying an instance of a model and updating fields

I'm trying to copy an instance of my Page model and set the new page's status to "draft." This code works perfectly in the Django shell, but in the admin action where it lives, a new instance is created but the status is not updated.

for page in pages:
        page.pk, page.id = None, None
        page.save()
        page.status = Page.DRAFT
        page.updated_at = datetime.now()
        page.save(force_update=True)

So the above code creates a new page, but does not change its status.

I think it might have something to do with Page having proxy models depending on the status (PublishedPage, DraftPage, etc.) I'm not sure what the problem is, though.

Upvotes: 1

Views: 132

Answers (2)

kgodey
kgodey

Reputation: 43

It turns out that the proxy models subclassing Page had custom save method overriding my updates.

Upvotes: 0

S.Lott
S.Lott

Reputation: 392050

Don't.

for page in pages:
    new_page= Page.objects.create(
        this= page.this, that=page.that, ...
        status= Page.DRAFT )

Much simpler. Much clearer. And it actually works.

Upvotes: 1

Related Questions