【发布时间】:2014-08-16 07:27:18
【问题描述】:
我想在 django 中显示两个带有外键的连接表的数据,我已经设置好了但它没有显示任何内容,这是我的文件:
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)
views.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
【问题讨论】:
-
在python中,方法和函数应该是小写的,带下划线。逗号和冒号后面应该跟一个空格。作业应该在
=周围有空格。而且,您想迭代subject_names,它不是一个查询集,而只是一个对象(get方法)。在您的模板中不要循环,只需使用{{subject_names.subject_name}}等。您对类和属性的命名也有点时髦。 -
@SteveK 不,这不是强制性的,我已经检查了所有这些并包括空格并从模板中删除了循环,但没有任何区别,我能够完美地使用管理面板很好,我在那里创建了管理模型,我可以输入对象并显示它们。空格不是强制性的`>>> a=1 >>> 打印一个 1
-
我不是说它是强制性的,它是关于编码约定和代码可读性的。如果你查看 StackOverflow 中的其他 python 代码,你会看到我正在谈论的模式。
标签: python mysql database django dynamic-data-display