Fetching data from multiple tables in Django

时间:2018-02-03 10:35:11

标签: django

How to perform a join query? I want to fire query which act like:

select s.nm,s1.sub from Student s,Subject s1

Here I show what I tried in Django but doesn't work:

My model.py file is

    from django.db import models    
    class Student(models.Model):
        sid = models.BigIntegerField(primary_key=True)
        nm = models.CharField(max_length=20, blank=True, null=True)
        id = models.ForeignKey('Subject', models.DO_NOTHING, db_column='id', blank=True, null=True)

        class Meta:
            managed = False
            db_table = 'student'


    class Subject(models.Model):
        id = models.IntegerField(primary_key=True)  # AutoField?
        sub = models.CharField(max_length=30, blank=True, null=True)

        class Meta:
            managed = False
            db_table = 'subject'

view.py

    from django.http.response import HttpResponse
    from django.core import serializers
    from App.models import Student, Subject
    # Create your views here.
    def fun(request):
      #  obj1=Subject.objects.all()
        obj=Student.objects.filter(Subject.objects.all()).all()
        js=serializers.serialize("json",obj)
        return HttpResponse(js)

but it doesn't work.

2 个答案:

答案 0 :(得分:0)

you should use related_name attribute in model, and you can access the object this way.

models.py

class Student(models.Model):
    sid = models.BigIntegerField(primary_key=True)
    nm = models.CharField(max_length=20, blank=True, null=True)
    subject = models.ForeignKey("Subject", related_name="student", blank=True, null=True)

class Subject(models.Model):
    sub = models.CharField(max_length=30, blank=True, null=True)

views.py

from App.models import Student, Subject
def myFunc():
    students = Student.objects.all()
    for student in students:
        subj = student.subject.sub

def myFunc2():
    subjects = Subject.objects.all()
    for subject in subjects:
        student_name = subject.student.nm

答案 1 :(得分:0)

正如您在模型中定义的那样,试试这个:

from App.models import Student, Subject 

def fun(request):
    subjects=Subject.objects.all()
    obj=Student.objects.filter(id__in=subjects)
    js=serializers.serialize("json",obj)
    return HttpResponse(js)