如何显示从子类别Django分离的类别

时间:2018-02-09 11:59:44

标签: python django

我创建了 model.py

from django.db import models
from django.contrib.auth.models import User


class Kategoria(models.Model):
    name = models.CharField(max_length=250, verbose_name='Kategoria')
    slug = models.SlugField(unique=True,verbose_name='Adres SEO')
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)

    class Meta:
        unique_together = ('slug', 'parent',)
        verbose_name = 'Kategoria'
        verbose_name_plural = 'Kategorie'

    def __str__(self):
        full_path = [self.name]
        k = self.parent

        while k is not None:
            full_path.append(k.name)
            k = k.parent

        return ' / '.join(full_path[::-1])

class Firma(models.Model):
    user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE)
    title = models.CharField(max_length=250, verbose_name='Nazwa firmy')
    slug = models.SlugField(unique=True, verbose_name='Adres SEO')
    category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE)
    content = models.TextField(verbose_name='Opis')
    draft = models.BooleanField(default=False, verbose_name='Szablon')
    publish = models.DateField(auto_now=False, auto_now_add=False)


    class Meta:
        verbose_name='Firma'
        verbose_name_plural='Firmy'

    def __str__(self):
        return self.title

此模型将类别创建为父类别,将子类别创建为子类别。之后我可以在Firma类中创建一个帖子并连接子类别或类别。在我的 view.py 中,我有:

from django.shortcuts import render, get_object_or_404
from .models import Kategoria, Firma



def widok_kategorii(request):
    kategorie = Kategoria.objects.all()
    context = {'kategorie': kategorie}
    return render(request, 'ogloszenia/index.html', context=context)

并在 html 文件中结束:

{% for kategoria in kategorie %}
{{kategoria.name}}<br>
{% endfor %}

在这种情况下,我在浏览器中所有记录都属于Kategoria类(类别和子类别在一起)。如何在视图中编写def以将类别和子类别分开,例如在附图中 enter image description here

最后,如何分析包含多少记录,例如类别:商业 - (256)??

1 个答案:

答案 0 :(得分:0)

执行此操作:

category=Kategoria.objects.filter(parent=None)
sub_category=Kategoria.objects.exlude(parent=None)