0

This seems to be fairly simple but the solution doesn't feel intuitive enough to me. Could not find an SO post with this exact question though.

I have a School model with a ManyToMany mapping to an Area model which then has a OneToMany mapping to a SubArea model.

class School(models.Model):
  area = models.ManyToManyField(Area, blank=True)
  sub_area = models.ManyToManyField(Area, blank=True)

class Area(models.Model):
  name = models.CharField(max_length=100, unique=True)

class SubArea(models.Model):
  name = models.CharField(max_length=100, unique=True)
  area = models.ForeignKey(Area, blank=True) 

A School object can belong to one or more Areas and optionally a specific SubArea within an Area but it doesn't feel quite intuitive to put sub_area in the School model because I feel that it should somehow be coming 'through' the area field, though I could be wrong. Does the above seem like the ideal way to model this?

Anupam
  • 14,950
  • 19
  • 67
  • 94
  • 2
    just remove `area` from `School` and get it value through the `SubArea` – Brown Bear May 24 '18 at 11:09
  • Actually I forgot to mention that some `School` instances may not have a `SubArea` and may just have an `Area` only. Updated the question to reflect this fact – Anupam May 24 '18 at 12:23
  • two way 1. if exists `sub_area` get area from it, in other case directly from `area`. 2. For each area create fake sub_area. – Brown Bear May 24 '18 at 12:26
  • Hmm, on further thinking, this seems to be similar to a Country->State->City scenario. I saw some examples online ([1](https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html),[2](https://stackoverflow.com/q/4071630/1526703)) and it seems common to use all 3 (Country, State and City) as fields in the main model (even if they have a parent child relationship). Perhaps I'll just go with the model in the question for now (unless someone has any other strong opinions) – Anupam May 24 '18 at 13:27

0 Answers0