[Answered ]-How to avoid making multiple trips to database in Django loop?

2๐Ÿ‘

โœ…

A lot of time, Django does a decent job caching database results. If you want to have more control, you could do something like this (provided that you do not have too many types)

class Point(models.Model):
    components = models.ArrayField(models.IntegerField(), default=[])

    def save_components(self, geocode):
        _components = []
        _types = {t.type: t for t in Type.objects.all()}
        for c in geocode:
            ct = _types.get(c['types'][0], None)
            if not ct:
                ct = Type.objects.create(type=c['types'][0])
            _components.append(Component.objects.get_or_create(long=c['long_name'], type=ct).pk)
        self.components = _components
        self.save()

This should save you looking up existing types all the time. You can also try to defer creating new Types and new Components (use get() instead of get_or_create() and catch the DoesNotExist exception) and use bulk insert later in the function (here is a doc link)

๐Ÿ‘คMad Wombat

Leave a comment