I have got a Stop model and a Service model. They form a ManyToMany relationship with each other.
This is done by using stops = models.ManyToManyField(Stop, related_name='services')
inside the Service model.
I would like to create new services and stops while making as few queries as possible. Currently, this is how I do it:
- Create all new services using
bulk_create
- Create all new stops using
bulk_create
- Retrieve all services from the database
- Retrieve all stops from the database
- Add the appropriate stops to each service
In this way, step 5 will produce as many queries as the number of services.
Is there a simpler way of saving ManyToMany relationships? Also, could I spare retrieving all services and stops right after creating them?
Service:
class Service(models.Model):
# Many to many relationship with Stop
stops = models.ManyToManyField(Stop, related_name='services')
name = models.CharField(max_length=5, blank=False, unique=True)
type = models.CharField(max_length=40, blank=False)
description = models.CharField(max_length=100, blank=False)
Stop:
class Stop(models.Model):
name = models.CharField(max_length=100, blank=False, unique=True)
latitude = models.FloatField()
longitude = models.FloatField()