0

我有一个使用 django-taggit TaggableManager 的模型:

from django.db import models

from model_utils import Choices
from taggit_autosuggest.managers import TaggableManager


LANGUAGE_CHOICES = Choices(
    ('de', 'Allemand - Deutch'),
    ('en', 'Anglais - English'),
    ('es', 'Espagnol - Español'),
    ('fr', 'Français'),
    ('it', 'Italien - Italiano'),
    ('jp', 'Japonais - 日本語'),
    ('ko', 'Coréen - 한국어'),
    ('pt', 'Portugais - Português'),
    ('th', 'Thaï - ไทย'),
    ('vi', 'Vietnamien - Tiếng Việt'),
    ('zh', 'Chinois - 中文'),
)


class Recipe(models.Model):
    language = language = models.CharField(
        max_length=5,
        choices=LANGUAGE_CHOICES,
        default=LANGUAGE_CHOICES.en
    )
    tags = tags = TaggableManager(
        help_text="Use tab to add a new term.",
        blank=True
    )

如何使用相关的食谱语言获取所有食谱标签?

4

1 回答 1

0

经过一番调查,我想出了以下解决方案:

GenericRelation在模型中添加一个Recipe

from django.contrib.contenttypes.fields import GenericRelation
from django.db import models

from model_utils import Choices
from taggit_autosuggest.managers import TaggableManager
from taggit.models import TaggedItem


LANGUAGE_CHOICES = Choices(
    ('de', 'Allemand - Deutch'),
    ('en', 'Anglais - English'),
    ('es', 'Espagnol - Español'),
    ('fr', 'Français'),
    ('it', 'Italien - Italiano'),
    ('jp', 'Japonais - 日本語'),
    ('ko', 'Coréen - 한국어'),
    ('pt', 'Portugais - Português'),
    ('th', 'Thaï - ไทย'),
    ('vi', 'Vietnamien - Tiếng Việt'),
    ('zh', 'Chinois - 中文'),
)


class Recipe(models.Model):
    language = language = models.CharField(
        max_length=5,
        choices=LANGUAGE_CHOICES,
        default=LANGUAGE_CHOICES.en
    )
    tags = tags = TaggableManager(
        help_text="Use tab to add a new term.",
        blank=True
    )

    related_tags = GenericRelation(TaggedItem, related_query_name='recipes')

然后您可以使用 TaggedItem 创建您的请求:

from taggit.models import TaggedItem
from django.db.models import Count

tags = TaggedItem.objects \
    .filter(content_type__app_label='recipes') \
    .values_list('tag__name', 'recipes__language') \
    .annotate(dcount=Count('tag_id', 'recipes__language'))
于 2018-03-20T11:01:38.223 回答