简体   繁体   中英

How to get the date from foreign Key column in Django

I am new to Django.I have two tables StatusTable and SystemTable in where the SystemTable has a foreign column "Status" where is stores the id of the status from StatusTable.The data save is working fine as expected. I need to show the Statusname of the system in a Statuspage but instead I am getting only the id of the status stored in SystemTable.

Models.py

class StatusTable(models.Model):
    status_name = models.CharField(max_length=20,default='')

    def __str__(self):
        return self.status

    class SystemTable(models.Model):
       sid = models.CharField(max_length=3)
       status = models.ForeignKey(StatusTable,null=True)

Viwes.py

def systemstatuspage(request):
    form = CreateTaskMaster()        
    task_title = SystemTable.objects.all()
    my_list = [ model_to_dict(x) for x in task_title]

    return render(request, 'task/task.html', {'form': form, 'sid':my_list})

在此处输入图片说明

No need to convert queryset to list manually, you can loop queryset in your template.

def systemstatuspage(request):
    form = CreateTaskMaster()        
    tasks = SystemTable.objects.all()
    # remove this line
    # my_list = [ model_to_dict(x) for x in task_title]
    return render(request, 'task/task.html', {'form': form, 's_ids':tasks})

and in template you can use foreign-key relation

{% for s in s_ids %}
   {{s.status.status_name}}
{% endfor %} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM