Sunday, October 23, 2022

Re: Sanity check please

Do you need to guarantee that any of this is atomic? If so then I usually wrap this kind of code in a "with transaction.atomic()".

If not, is all this slowing down your UX? If so, then you might consider doing some of this in an asynchronous task after the save using celery or something like it.  If not, then what you have is fine.

On October 23, 2022 2:52:36 AM CDT, Mike Dewhirst <miked@dewhirst.com.au> wrote:
In the Django Admin I have a model central to a bunch of FKs and M:Ms plus a lot of processing on saving.

This is my solution which seems to work but frightens me a bit.

class Chemical(models.Model):
      # lots of fields
      def save(self, *args, **kwargs):
        self.process_stuff_based_on_field_values_pre_save()
        first = False
        if not self.id:
            first = True
            super().save(force_insert=True, *args, **kwargs)
        if self.id:
            self.create_or_update_a_bunch_of_related_records(first=first)
        super().save(force_insert=False, *args, **kwargs)
        self.create_or_update_a_bunch_of_m2m_records(first=first)
      def process_stuff_based_on_field_values_pre_save(self, first=False):          ...            def create_or_update_a_bunch_of_m2m_records(self, first=False):          ...          # lots of other methods
  
Thanks for any warnings, caveats

Cheers

Mike

--   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.  

No comments:

Post a Comment