Fetching model instance from a multiple direct relationship
<p>Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now.</p>

<p><strong>First I would like to get all distinct <code>SubSpecialization</code> from all <code>Doctor</code> which has a given <code>Specialization.title</code></strong></p>

<p><strong>Secondly I would like to get all <code>Doctor</code> which has a specific <code>Specialization.title</code> and has no <code>SubSpecialization</code>.</strong></p>

<p>Here is the <code>Doctor</code> model</p>

<pre><code>class Doctor(models.Model):
    name = models.CharField(max_length=50)
    room_no = models.IntegerField()
    floor_no = models.IntegerField()
    contact_no = models.CharField(max_length=50, blank=True, null=True)
    notes = models.CharField(max_length=70, blank=True, null=True)
</code></pre>

<p>This is the model <code>Doctor</code> relationship is connected to <code>Specialization</code>and <code>SubSpecialization</code>.</p>

<pre><code>class DoctorSpecialization(models.Model):
    doc = models.ForeignKey(Doctor, models.DO_NOTHING)
    spec = models.ForeignKey('Specialization', models.DO_NOTHING)

class DoctorSubSpecialization(models.Model):
    doc = models.ForeignKey(Doctor, models.DO_NOTHING)
    sub_spec = models.ForeignKey('SubSpecialization', models.DO_NOTHING)
</code></pre>

<p>This is where i would make a criteria.</p>

<pre><code>class Specialization(models.Model):
    title = models.CharField(unique=True, max_length=45)
    point = models.IntegerField()

class SubSpecialization(models.Model):
    title = models.CharField(max_length=100)
</code></pre>

<p>There is no direct relationship between the <code>Specialization</code> and <code>SubSpecialization</code> please help.</p>

<p>Firstly, your specialization and subspecialization are both many-to-many relationships with Doctor. You should declare that explicitly, and drop those intervening models unless you need to store other information on them.</p>

<pre><code>class Doctor(models.Model):
    ...
    specializations = models.ManyToManyField('Specialization')
    subspecializations = models.ManyToManyField('SubSpecialization')
</code></pre>

<p>Now you can query for all the subspecializations for doctors who have a specific specialization:</p>

<pre><code>SubSpecialization.objects.filter(doctor__specialization__title='My Specialization')
</code></pre>

<p>Your second query doesn't make sense given the fact there is no relationship between specialization and subspecialization, you'll need to clarify what you mean by "no subspecialization in a specific specialization".</p>

<p><strong>Edit</strong></p>

<p>To find doctors who have a specific Specialization and then no subspecializations at all:</p>

<pre><code>Doctor.objects.filter(specialization__name="My Specialization",
                      subspecialization=None)
</code></pre>

python django django-models