Search code examples
pythondjangoforeign-key-relationshiprelationships

How can I get the foreign key object value?


I have 3 tables as follows. User table has student info. LecMst table has lecture info. And LecReq table has lecture info students have registered.

models.py

class User(models.Model):    
    usn = models.CharField(max_length=20, primary_key=True, verbose_name='usn')
    nm = models.CharField(max_length=50, blank=True, null=True, verbose_name='name')
    userid = models.CharField(max_length=20, blank=True, null=True, verbose_name='ID')

class LecMst(models.Model):
    leccode = models.CharField(max_length=15,  null=False, primary_key=True, verbose_name='lecture_code')
    lecname = models.CharField(max_length=100,  null=True, verbose_name='lecture_name')

class LecReq(models.Model):
    leccode_id = models.ForeignKey(LecMst,  db_column='leccode', verbose_name='lecture_code', related_name = 'lecreqs')
    usn_id = models.ForeignKey(User, db_column='usn', verbose_name='usn', related_name = 'lecreqs')

students_by_lecture.html shows student list in the specific class. And the page I want to show student name, and lecture name besides leccode_id, usn_id.

lectures.py

def student_list_by_lecture(request):

    qs_leccode = request.GET['leccode']

    if qs_leccode:

        qs = LecReq.objects.filter(leccode_id=qs_leccode)

        paginator = Paginator(qs, 25) # Show 25 posts per page
        page = request.GET.get('page')
        try:
            lecture_members = paginator.page(page)
        except PageNotAnInteger:
            lecture_members = paginator.page(1)
        except EmptyPage:
            lecture_members = paginator.page(paginator.num_pages)

    return render(request, 'students_by_lecture.html', {
        'lecture_members' : lecture_members,
        'qs_leccode' : qs_leccode,
    }) 

Below is students_by_lecture.html What can I input ????.

 <table>
    <thead>
        <tr>
            <th>Lecture Code</th>
            <td>Lecture Name</td>
            <td>Student Name</td>
            <td>Student No (usn)</td>
        </tr>
    </thead>
    <tbody>{% for member in lecture_members %}
        <tr>
        <td>{{ member.????? }}</td>
        <td>{{ member.????? }}</td>
        <td>{{ member.????? }}</td>
        <td>{{ member.????? }}</td>
        </tr>{% endfor %}
    </tbody>
</table>                            

Solution

  • The related objects can be accessed easily as:

    {{ member.leccode_id.lecname }}
    

    More information on Django Docs: Lookups that span relationships.

    Please also notice that your naming convention is strictly speaking wrong. You should name the field by its entity name, leccode and not leccode_id, because now to access the id of the entity you should use leccode_id_id.