[英]Show list of related objects in a template Django
我在 Q&A DetailView 中显示相关文章列表时遇到问题。 我有一个字段,用户可以在其中将文章从管理站点连接到问答。 我想要的是展示这些相关的文章。
模型.py
class QA(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField(max_length=750)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True)
related_articles = models.ManyToManyField(Article, default=None, blank=True, related_name='related_article')
slug = models.SlugField(unique=True, blank=True)
class Article(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True)
slug = models.SlugField(unique=True, blank=True)
视图.py
class QADetailView(LoginRequiredMixin, DetailView):
login_url = 'login'
redirect_field_name = 'login'
template_name = 'QADetailView.html'
model = QA
def get_context_data(self, **kwargs):
categories = Category.objects.all()
related_articles = Article.objects.filter(related_article=self.kwargs['id']) #No idea what to put in filter
#related_articles = Article.objects.filter(related_article='1')
context['related_article'] = related_articles
context['categories'] = categories
return context
QADetailView.html
{% for article in related_article %}
{{article.title}}
{% endfor %}
您不需要在模板上下文中注入相关文章,您可以简单地在您的QADetailView.html
模板中编写(无需任何必要的编辑):
{% for article in object.related_articles.all %}
{{article.title}}
{% endfor %}
首先检查 RedWheelBorrow 的解决方案。 如果这不起作用。 尝试以下操作:
可能有更好的方法来构建你的类。 所以在 Django 中,可以模拟层次结构。 例如,在创建发票表示时,它看起来像这样。
from django.db import models
class Invoice(models.Model):
"""Representing a invoice"""
user = models.ForeignKey(to=User, on_delete=models.PROTECT, related_name="invoices", default=1)
title = models.CharField(max_length=200)
date = models.DateField()
start_time = models.TimeField(default=time(9))
duration = models.IntegerField(default=1)
invoice_number = models.CharField(max_length=500, default=increment_invoice_number) # increment_invoice_number this a function that I will leave out of this answer
class InvoiceLine(models.Model):
"""Representing invoice lines of an invoice"""
invoice = models.ForeignKey(to=Invoice, on_delete=models.CASCADE, related_name="lines")
description = models.CharField(_("Beschrijving"), max_length=512)
quantity = models.IntegerField(_("Aantal"), blank=True, default=1)
discount = models.IntegerField(_("Korting in %"), default=0)
请注意,此处提供的发票表示缺少某些属性,无法在生产中成为功能齐全的 class。 它仍然需要税务参考等。但是,它可以解决您的问题。
Invoice class 有一个属性 user ,它持有一个 ForeignKey ,“invoices”是它的相关名称。 这意味着 object 必须链接到用户 object。 一个用户可以有多个发票。 一张发票只能链接到一个用户。 这是一对多的关系:
用户 -> 列表[发票,...]
查看 class InvoiceLine 时,我们看到了类似的模式。 属性 invoice 是一个 ForeignKey,带有到 Invoice class 的链接,并持有“lines”作为相关名称。 这也是一对多的关系。
发票 -> 列表[InvoiceLine, ...]
要获取链接的对象,我们可以使用以下代码:
# obtain user
user = User.objects.get(id=<USER_ID>)
# obtain all Invoice objects linked to user
invoices = user.invoices.all()
# print all string representations of Invoice objects
print(invoices)
# obtain all InvoiceLine objects linked to invoices
for invoice in invoices:
lines = invoice.lines.all()
print(lines)
在上面的例子中,最高的 object 是用户。 一个用户可以持有多个发票对象。 一个 Invoice object 可以容纳多个 InvoiceLine 对象。 我们可以使用相同的策略来解决您的问题。
我们想要以下表示:
用户 -> 列表[QA,...] QA -> 列表[文章,...]
class QA(models.Model):
id = models.AutoField(primary_key=True)
# So in your case the author is the user.
# Here you define User -> List[QA, ...]
author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField(max_length=750)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True)
slug = models.SlugField(unique=True, blank=True)
# related_articles is removed.
class Article(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True)
slug = models.SlugField(unique=True, blank=True)**
related_articles = models.ForeignKey(to=QA, on_delete=models.CASCADE, related_name="related_articles")
class QADetailView(LoginRequiredMixin, DetailView):
login_url = 'login'
redirect_field_name = 'login'
template_name = 'QADetailView.html'
model = QA
def get_context_data(self, **kwargs):
categories = Category.objects.all()
# obtain specific QA
qa = QA.objects.get(pk=id, author=self.request.user)) # check how you named the id variable in your url.
# obtain related articles
related_articles = qa.related_articles.all()
# Save in context for use in template.
context['related_articles'] = related_articles # Added an character 's' to key value for there is can be more than one related article.
context['categories'] = categories
return context
{% for article in related_articles %} # Also add character 's' here
{{article.title}}
{% endfor %}
这应该可以解决问题。 尽管我希望这可行,但错误处理可能会有一些改进。 如果没有,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.