我想使用多对多表格来参考要在我的网站页面上显示的专业
Model.py
from django.db import models
class Major(models.Model):
name = models.CharField(max_length=30, db_index=True)
class School(models.Model):
name = models.CharField(max_length=50, db_index=True)
school_Major_merge = models.ManyToManyField(Major, through='School_Major')
class School_Major(models.Model):
major = models.ForeignKey(Major, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
#delete major from the model
school = models.ForeignKey(School , on_delete=models.CASCADE)
major = models.ForeignKey(Major , on_delete=models.CASCADE)
def __str__(self):
return self.ProfessorName
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import professor, School , School_Major, Major
def index(request):
# professors = professor.objects.all()
# return render(request, 'locate/index.html', {'professors': professors})
schools = School.objects.all()
return render(request, 'locate/index.html', {'schools': schools})
def Major(request, Major):
major_choice = professor.objects.filter(Major =Major)
return render(request, 'locate/major.html', {'major_choice': major_choice})
url.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:Major>/', views.Major, name='Major')
]
基本上,我正在尝试找出我的观点。在选择特定学校时,我将能够使用School_Major专门引用要显示在我网站主要部分中的专业,
在我的index.html上,我有以下for循环
<ul>
{% for list in schools %}
<li><a href="{% url 'view' '{{list.id}}' %}">{{list.name}}</a></li>
<br><br>
{%endfor%}
</ul>
“视图” 是一种功能,它将采用School PK并使用School_Major表来引用该学校可以使用的专业,并显示“专业”。
我将为每个表格提供示例图片,以实现更直观的显示。
学校
答案 0 :(得分:0)
我不知道您为什么创建School_Major模型。
访问M2M。 在模型下方添加功能
def get_yourfunctionname(self):
return ", ".join([x.field_you_want for x in self.your_M2M_Field_name.all()])
在模板中
<ul>
{% for list in schools %}
<li><a href="{% url 'view' '{{list.id}}' %}">{{list.get_yourfunctionname}}</a></li>
<br><br>
{%endfor%}
</ul>