【发布时间】:2019-03-27 19:01:24
【问题描述】:
我已经很好地阅读了有关 ManyToMany 归档的 Django 文档。尤其是here 。我很清楚可以用它做的事情。例如,如果我有一个 Category 模型和一个 Startup 模型,其中一个类别可以有许多初创公司,而一个初创公司可以属于许多类别,那么 ManyToMany 关系在这里很有用。我可以在我的模板上列出所有类别,每个类别都是可点击的,并导致属于该类别的另一个模板上的所有初创公司的列表。 现在,有了这个,我想更进一步。转到特定类别的详细信息页面,这是属于它的初创公司的列表,我希望此详细信息页面中的每个项目也指向另一个详细信息页面,我可以在其中显示有关特定初创公司的更多信息。
我现在的主要问题是如何实现它。我已经处理了许多与 ManyToMany 字段及其查询相关的问题,尤其是here,但它们似乎都在讨论如何将相关对象访问到某个类别,例如在详细信息页面中,并且到此为止。我想从详情页转到另一个详情页。
from django.db import models
我的类别模型:
class Category(models.Model):
name = models.Charfield(max_length=100)
def __str__(self):
return self.name
def get_startups(self):
return Startup.objects.filter(category=self)
我的创业模型:
class Startup(models.Model):
name = models.CharField(max_length=100)
founder_name = models.CharField(max_length=100)
short_description = models.CharField(max_length=225)
concept = models.TextField(help_text='how does this startup operate?')
category = models.ManyToManyField(Category)
website = models.URLField(max_length=225)
logo = models.ImageField()
def __str__(self):
return self.name
@property
def logo_url(self):
if self.logo and hasattr(self.logo, 'url'):
return self.logo.url
在我的views.py文件中:
class CategoryView(ListView):
template_name = 'myapp/startup-category.html'
context_object_name = 'category_list'
def get_queryset(self):
return Category.objects.all()
class DetailView(DetailView):
model=Category
template_name = 'myapp/startup-list.html'
在我的模板/myapp/startup-category 中:
{% if category_list %}
<ul>
{% for category in category-list %}
<li><a href="{% url 'detail' category.pk %}">{{category.name}}</a></li>
{% endfor %}
</ul>
{% endif %}
在模板/myapp/startup-list.html 中:
{% for startup in category.get_startups %}
<tr>
{% if startup.logo %}
<td><img src="{{ startup.logo_url|default_if_none:'#' }}" style="height: 50px; width: 50px;"></td>
{% endif %}
<td>{{startup.name}}</td>
<td> {{startup.short_description}}</td>
<td>
<button type="button" ><a href="">View startup</a>
</button></td>
</tr>
{% endfor %}
在 myapp.urls 中:
from django.urls import path
from . import views as core_views
path('startup_categories/', core_views.CategoryView.as_view(), name='startups'),
path('startup_categories/<int:pk>/', core_views.DetailView.as_view(), name='detail'),
这很好用。我得到一个类别列表;当我点击一个类别时,它会将我带到一个详细信息页面,在该页面中,我会以表格形式获取与该类别相关的初创公司列表。在每个启动元素上,都有一个用于查看启动详细信息的按钮。 如何实现启动详情视图?
提前感谢您!
【问题讨论】:
标签: django django-templates django-views manytomanyfield