[英]Django get all post of a parent category
我是 django 3 的初學者,我決定創建一個簡單的博客來實踐我學到的東西。
我創建了一個帶有外鍵類別的帖子 model 和一個帶有自外鍵的 model 類別。 一切都很好,我找到了一種方法來創建我的菜單,問題是當我點擊父級時,我想為子菜單發布所有帖子。
例如,我有這個菜單:
*信息 * Django * HTML - CSS
*形象的
如果我點擊 django,我有我所有的 django 帖子,與 html-css 相同,但現在我想要所有信息性帖子,有 django + html-css 的帖子。
我可以修改我的 model 帖子,而不是在外鍵中有一個帶有類別的字段,我可以使用一個多字段。 但我不想要它,因為我可能忘記放入信息或其他類別。 那么我能做些什么,以一種簡單的方式?
你能向我解釋一下做什么和如何做,以及我需要在哪里放置代碼
我不確定你需要什么代碼,但是有:
class Category(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=250, null=True, blank=True)
menu = models.BooleanField(default=False, null=True, blank=True)
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,related_name='subcategory')
def children(self):
"""Return replies of a comment."""
return Category.objects.filter(parent=self, menu=1)
@property
def is_parent(self):
"""Return `True` if instance is a parent."""
if self.parent is not None:
return False
return True
def __str__(self):
return self.title
class CategoryManager(models.Manager):
def all(self):
"""Return results of instance with no parent (not a reply)."""
qs = super().filter(parent=None)
return qs
我的帖子版本沒有其他字段
class Post(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, default=1)
在我的菜單模板中:
<ul>
{% for category in categories%}
{% if not category.parent %}
<li><a href="{% url 'category-post' cslug=category.slug%}">{{ category.title }}</a></li>
{% for subcategory in category.children %}
<li>
<a href="{% url 'category-post' cslug=subcategory.slug %}">--- {{ subcategory.title }}</a>
</li>
{% endfor %}
{% endif %}
{% endfor %}
</ul>
和視圖
def category_post(request, cslug ):
posts = Post.objects.filter(category__slug=cslug)
category = Category.objects.get(slug=cslug)
context = {
'category': category,
'posts': posts,
}
return render(request, 'blog/category_post.html', context)
如果您需要更精確,請告訴我:)
在 Post model REF: DOCS
您將能夠從具有相關名稱的類別中調用帖子...因此,如果您設置了相關名稱relate_name='posts'
,則意味着您將訪問該類別中的帖子,例如category.posts.all()
或category.posts.filter()
或category.posts.all()[slice]
我太累了,我什至沒有注意到我在我的 model 中創建了一個 def,我將它與你的答案一起使用,現在它正在工作。 謝謝你們倆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.