Currently this code seems to be going to the database (Postgres) two to four times on every loop iteration. First to get (and create) the Type, then to get (and create) the Component. Is there a way to do this in fewer database trips?
models.py:
class Component(models.Model):
long = models.TextField()
type = models.SmallForeignKey('Type', models.CASCADE)
class Type(models.Model):
type = models.TextField(unique=True)
class Point(models.Model):
components = models.ArrayField(models.IntegerField(), default=[])
def save_components(self, geocode):
_components = []
for c in geocode:
ct = Type.objects.get_or_create(type=c['types'][0])
_components.append(Component.objects.get_or_create(long=c['long_name'], type=ct).pk)
self.components = _components
self.save()
Incoming data:
geocode = [
{
"long_name" : "Luray",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Page County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Virginia",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"types" : [ "country", "political" ]
}
]
ctandcomponentdon't come out of nowhere, they are fetched from database, how can you not hit the database and get the information?TypeandComponentexists, each costs one sql query, no doubt about that. If they don't exist, you have to create them, another 1 or 2 creation sql statements will be sent to the database. I'm not sure what do you meanall information is already there, don't you want to create them when if are not stored? Also as @DanielRoseman said: docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many