jas
jas

Reputation: 57

I want to get result of two query data using ORM in django

I want to get result of two query data using ORM in django but only one data is being displayed. How may i resolve this?

My codes:

views.py

def home(request):
    
    codes, descrp = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages p, major m WHERE p.major_cd = m.major_cd;')
    context = { 
               "codes": codes,
               "descrp": descrp
    }
 return render(request, "website/index.html" , context )

index.html

<select class="form-control select2">
   <option>Select Major Head</option> 
   {% for cd, ds in codes, descrp %}
    <option> {{ cd, ds }} </option> 
    {% endfor %} 
    </select>

Models

class Major(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    description = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'major'

class Percentages(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    percentage = models.CharField(max_length=5, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'percentages'

I want to filter out 'major_cd' in major table based on 'major_cd' in percentages table.

Expected Results: Data with column = major_cd, description from major table

Upvotes: 2

Views: 166

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476567

It looks to me that it might be better to rewrite the model to a ForeignKey, this makes querying in Django more convenient:

class Major(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    description = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'major'

class Percentages(models.Model):
    major_cd = models.OneToOneField(
        Major,
        on_delete=models.CASCADE,
        primary_key=True,
        db_column='major_cd'
    )
    percentage = models.CharField(max_length=5, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'percentages'

Once this is done, we can query with:

def home(request):
    majors = Major.objects.filter(percentage__isnull=False)
    context = { 
        'majors': majors
    }
    return render(request, 'website/index.html', context)

In the template, we can then render this with:

<select class="form-control select2">
  <option>Select Major Head</option> 
  {% for major in majors %}
    <option>{{ major.pk }}: {{ major.description }}</option> 
  {% endfor %} 
</select>

Upvotes: 2

Abdulla Osama
Abdulla Osama

Reputation: 179

you can use Q, from django.db.models import Q.

for example you can make it like .. descrp = Major.objects.filter(Q(major_cd=.major_cd) & Q(m_description=m.description))

Upvotes: 0

Related Questions