Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - ManyToMany relation without the cross table

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  |
+----+---------------+------------+
like image 873
hustas88 Avatar asked Sep 20 '25 03:09

hustas88


2 Answers

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)
like image 124
Jedi Avatar answered Sep 21 '25 15:09

Jedi


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.

like image 30
Daniel Roseman Avatar answered Sep 21 '25 17:09

Daniel Roseman