如何使用 Django ORM 过滤带有相关项目字段的标签



我有一个模型,我在其中使用 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
    )

如何获取所有食谱标签及其相关食谱语言?

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

Recipe模型添加GenericRelation

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')

然后,您可以使用标记项创建请求:

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'))

相关内容

  • 没有找到相关文章

最新更新