2013-11-24 86 views
0

我使用django-categories來實現音樂相關的應用程序。我想藝術家爲我的類別和他/她作爲兒歌django類別:如何使用django類別獲得某個類別的子項?

models.py

from django.db import models 
from django_extensions.db.fields import AutoSlugField 
from categories.models import CategoryBase 

class Artist(CategoryBase): 
    cat = models.CharField(max_length=255, blank=True) 

    def __unicode__(self): 
     return self.name 

class Song(models.Model): 
    title = models.CharField(max_length=255,) 
    slug = AutoSlugField(populate_from='title', unique=True) 
    description = models.TextField() 
    cat = models.ForeignKey(Artist, blank=True) 

    def __unicode__(self): 
     return self.title 

模板,artist_details.html

{% extends 'base_post.html' %} 
{% load category_tags %} 
{% block page_content %} 

<h1>{{ artist.name }}</h1> 

{% if artist.children.count %} 
    <h2>Subcategories</h2> 
    <ul> 
     {% for child in artist.children.all %} 
     <li><a href="{{ child.get_absolute_url }}">{{ child }}</a></li> 
     {% endfor %} 
    </ul> 
{% endif %} 

模板是越來越呈現怎麼我可以看到藝術家名稱。但我無法取孩子。我查看了文檔,但找不到與提取兒童相關的許多內容。

我的數據庫中有兩個模型的數據,我通過管理界面添加了相關信息。任何人都可以告訴我我錯過了什麼嗎?

此外我打開使用更好的軟件包。你可以給出任何實現類別的建議。

解決方案:從Django文檔,即使使用Django類別https://docs.djangoproject.com/en/1.6/topics/templates/#accessing-method-calls

感謝mariodev

+1

我認爲當你的子類的分類模型,你不能用'孩子'再也。嘗試使用'song_set'來代替。 – mariodev

+0

按song_set你指的是queryset?如果沒有,你可以進一步解釋你的意思,或者給我一些有用的網頁鏈接,我可以進一步挖掘? –

回答

0

,你不能有歌曲的藝術家的兒童。藝術家只是不構成一個類別。

你,而不是需要的是這樣的:

from django.db import models 
from django_extensions.db.fields import AutoSlugField 
from categories.models import CategoryBase 

class MusicCategory(CategoryBase): 
    # add extra fields, like images, "featured" and such here 
    pass 

class Artist(CategoryBase): 
    name  = CharField(max_length=255,) 
    categories = models.ManyToManyField(MusicCategory, related_name="artists") 

    def __unicode__(self): 
     return self.name 

class Song(models.Model): 
    slug  = AutoSlugField(populate_from='title', unique=True) 
    title  = models.CharField(max_length=255,) 
    artist  = models.ForeignKey(Artist, related_name="songs", on_delete=models.PROTECT) 
    categories = models.ManyToManyField(MusicCategory, related_name="songs") 
    description = models.TextField() 

    def __unicode__(self): 
     return self.title 

,並與一些模板

{% extends 'base_post.html' %} 
{% load category_tags %} 
{% block page_content %} 

<h1>{{ artist.name }}</h1> 

{% if artist.songs.all.exists %} 
    <h2>Songs</h2> 
    <ul> 
     {% for song in artist.songs.all %} 
     <li><a href="{{ song.get_absolute_url }}">{{ song }}</a></li> 
     {% endfor %} 
    </ul> 
{% endif %} 

REF:https://django-categories.readthedocs.org/en/latest/custom_categories.html#creating-custom-categories

相關問題