我用model-slug创建了一些链接。但是当我单击我的链接时,转到页面但返回空值。我想当我点击任何链接时,它将查询所选字段中的值,如class_name或slug字段。
此课程列表html页面
{% extends "result/base.html" %}
{% block title %}Class List Name{% endblock title %} {% block content %}
<div class="row">
<div class="col-md-12 col-xs-offset-4">
<h2>Class List</h2>
{% for object in object_list %}
<a href="{% url 'result:class-detail' object.slug %}">{{object.class_name}}</a>
{% endfor %}
</div>
</div>
{% endblock %}
这是models.py文件
class ClassName(models.Model):
class_name=models.CharField('Class Name', max_length=10)
class_added=models.DateTimeField(auto_now_add=True)
class_updated=models.DateTimeField(auto_now=True)
slug=models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.class_name
这是views.py文件
class ClassListView(ListView):
model=ClassName
slug_field = 'slug'
template_name='result/class_list.html'
class ClassDetailView(DetailView):
model=ClassName
slug_field = 'slug'
template_name='result/class_detail.html'
def get_context_data(self,*args, **kwargs):
context = super(ClassDetailView, self).get_context_data(*args,**kwargs)
context['class_wise_std'] = StudentInfo.objects.filter(
student_class_name__class_name__startswith=self.model.slug)
return context
这是课程详情html页面
{% extends "result/base.html" %}
{% block title %}Class Detail's List{% endblock title %}
{% block content %}
<div class="row">
{% for object in class_wise_std %}
<div class="col-lg-12 col-sm-offset-4" style="margin:20px 10px">
<p>Name: {{object.student_name}}</p>
<p>Class: {{object.student_class_name}}</p>
<p>Father's Name: {{object.student_father_name}}</p>
<p>Mother's Name: {{object.student_mother_name}}</p>
<p>Roll: {{object.student_roll}}</p>
</div>
{% endfor %}
</div>
{% endblock content %}
此代码
def get_context_data(self,*args, **kwargs):
context = super(ClassDetailView, self).get_context_data(*args,**kwargs)
context['class_wise_std'] = StudentInfo.objects.filter(
student_class_name__class_name__startswith=self.model.slug)
return context
我发现此问题会发生此问题。我想使用 ClassName 模型中的 class_name 字段进行过滤。
StudentInfo.objects.filter(student_class_name__class_name__startswith=self.model.slug)
但我可以通过这种方式成功查询我的目标信息。
StudentInfo.objects.filter(student_class_name__class_name__startswith='One')
但这不是一种有效的方式。现在,我该如何动态实现这个?