0

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:

  1. Create all new services using bulk_create
  2. Create all new stops using bulk_create
  3. Retrieve all services from the database
  4. Retrieve all stops from the database
  5. 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()
Marlyyy
  • 702
  • 1
  • 6
  • 17

0 Answers0