Model switching - how to avoid saving twice

29 views
Skip to first unread message

Mike Dewhirst

unread,
Aug 15, 2022, 2:42:45 AM8/15/22
to Django users
Django 3.2 Admin

I have a model with two 1:n models and need to convert one type of model
into the other.

I know this sounds mad but it is a specialised document management to-do
system. It has Note models and Link models connected to the main model.

When converting a Note into a Link the Link gets created and the Note
gets deleted. This currently happens in the main model.save() after
calling super().

The method removes the Note from the to-do side and puts it on the done
side as a Link complete with a URL.

So far I can only detect if the user wishes to convert a Note into a
Link after the Note is saved with True in its conversion field.

That means the main model needs to be saved to commit that True value
and then saved again to convert any Notes with that True value.

The crux of the problem (to me) is that I'm using a queryset to detect
Notes in the database ready for conversion into links.

Is it possible to do this saving only once?

Thanks

Mike


class Chemical(models.Model):
    ...
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.convert_notes_to_links(line=line)

    def convert_notes_to_links(self, line=None):
        for note in Note.objects.filter(chemical=self, link=True):
            link, new = Link.objects.get_or_create(chemical=self,
name=note.title)
            if new:
                link.synopsis = note.note
                link.save()
                note.delete()






--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.

OpenPGP_signature
Reply all
Reply to author
Forward
0 new messages