Question

i am new to Django, and i having trouble understanding how the model.ManyToMany works. I have this model:

from django.db import models

class Health_plan(models.Model):
    a = models.IntegerField ()
    b = models.IntegerField ()

class Doctors_list(models.Model):

    name = models.CharField(max_length=30)
    hp_id = models.ManyToManyField(Health_plan)

    def __unicode__(self):
        return self.name

The doctor has a name and a list of N health plans. A health plan can be owned by N doctors. I see this as a N:N relationship, so i use ManyToMany to make the relations.´

The problem is the fact that this code generates 3 tables. Health_plan, Doctors_list and hp_id. What is the point? I can identify a doctor by it's id and match it with the id of the health plan.

The health plan table has in this example plan a and b and from default an id. The Doctor id = 5 , will have the plans marked as 1 (1 for true, 0 for false) on the row with id = 5 on Health_plan table.

Should i use another model? Hints?

Was it helpful?

Solution

Any many-to-many relationship, not just in Django, requires a linking table.

You say "I can identify a doctor by its id and match it with the id of the health plan" - well, that's exactly what the linking table does. Where else would that data go? As you say, each doctor has many plans, and each plan has many doctors. So there's no way to store that data on either the doctor's side, or the plan's side, since you need many entries. The linking table achieves that, by having many entries for each doctor, and many entries for each plan, but only one for each combination of doctor+plan.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top