简体   繁体   English

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

[英]How to filter taggit tags with related items fields using the Django ORM?

I have a model where I use the django-taggit TaggableManager: 我有一个使用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
    )

How can I grab all the recipes tags with their related recipe language? 如何获取所有配方标签及其相关的配方语言?

After investigation a little bit, I came up with the following solution: 经过一些调查,我提出了以下解决方案:

Add a GenericRelation to the Recipe model: 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')

Then you can use the TaggedItem to create your request: 然后,您可以使用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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM