I have 2 models: City and Service. Each city record can contain many services and each service can be linked to each city.
class City(models.Model):
name = models.CharField(max_length=255, unique=True)
class Service(models.Model):
name = models.CharField(max_length=255, unique=True)
class CityService(models.Model):
city = models.ForeignKey(City)
service = models.ManyToManyField(Service)
I use ManyToManyField to enable the multiple selections in Django admin. But Django creates one more table to store m2m relations..
Is it possible to configure Django models so that to reach the following table structure:
+----+---------------+------------+
| id | city_id | service_id |
+----+---------------+------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
+----+---------------+------------+
Why not just use a structure like:
class Service(models.Model):
name = models.CharField(max_length=255, unique=True)
class City(models.Model):
name = models.CharField(max_length=255, unique=True)
service = models.ManyToManyField(Service)
There is no need for the CityService table at all. A ManyToManyField already implies a join table; you are creating a second one, to no purpose at all. Have the M2M directly between City and Service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With