django で外部キーを使用して 2 つの結合されたテーブルのデータを表示したいのですが、すべて設定しましたが、何も表示されません。ここに私のファイルがあります。
models.py:
from django.db import models
from django.utils.encoding import smart_unicode
class Course (models.Model):
Course_name=models.CharField(max_length=120,null=False,blank=False)
course_id=models.AutoField(primary_key=True)
course_idtomatch=models.IntegerField(max_length=2)
def __unicode__(self):
return smart_unicode(self.Course_name)
class Subjectsnames(models.Model):
subject_name=models.CharField(max_length=50)
course=models.ForeignKey(Course)
def List item__unicode__(self):
return smart_unicode(self.subject_name)
ビュー.py:
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import Subjectsnames
from .models import Course
def Subjects(request):
Subject = Subjectsnames.objects.get(id=id)
subjects_data = {
"subjects_names":Subject
}
print subjects_data
return render_to_response("code.html",subjects_data,context_instance=RequestContext(request))
code.html:
<html>
{% for name in Subjectsnames %}
Name:{{name.subject_name}}
Id:{{name.id}}
{% endfor %}
</html>
そして、私はデータベースにこれらのデータを持っています:
件名:
+----+-----------------+-----------+
| id | subject_name | course_id |
+----+-----------------+-----------+
| 2 | Organic | 1 |
| 3 | inorganic | 1 |
| 4 | thermodynacmics | 2 |
| 5 | vectors | 2 |
| 6 | trigo | 3 |
| 7 | algebra | 3 |
| 8 | relational | 3 |
| 9 | c++ | 4 |
| 10 | c# | 4 |
+----+-----------------+-----------+
コース:
+-------------+-----------+------------------+
| Course_name | course_id | course_idtomatch |
+-------------+-----------+------------------+
| chemistry | 1 | 1 |
| pyhics | 2 | 2 |
| maths | 3 | 3 |
| computers | 4 | 4 |
+-------------+-----------+------------------+
course_idtomatch を無視
私の知る限り、code.html の for ループで何か間違ったことをした可能性があります。誰かがそれを解決するのを手伝ってください知っているなら、事前に感謝します。
私は自分のviews.pyを次のように更新しました:
from django.conf import settings
settings.configure()
from django.shortcuts import render, render_to_response, RequestContext
from django.db import models
from .models import Course
from .models import Subjectsnames
def Subjects(request):
Subject = Subjectsnames.objects.get(id=id)
subjects_data = {
"subjects_names":Subject
}
print subjects_data
return render_to_response("code.html",subjects_data,context_instance=RequestContext(request))
print Subject
しかし、端末で python views.py を実行すると、次のようなエラーが表示されます。
Traceback (most recent call last):
File "views.py", line 7, in <module>
from .models import Course
ValueError: Attempted relative import in non-package