Domanda

class Tag(models.Model):
  name = models.CharField(maxlength=100)

class Blog(models.Model):
  name = models.CharField(maxlength=100)
  tags =  models.ManyToManyField(Tag)

Modelli semplici solo per porre la mia domanda.

Mi chiedo come posso interrogare i blog usando i tag in due modi diversi.

  • Articoli di blog che sono taggati con " tag1 " o " tag2 " ;: Blog.objects.filter (tags_in = [1,2]). Distinta ()
  • Oggetti blog che sono taggati con " tag1 " e " tag2 " : ?
  • Gli oggetti blog che sono etichettati esattamente con " tag1 " e " tag2 " e nient'altro: ??

Tag e Blog sono solo usati per un esempio.

È stato utile?

Soluzione

Puoi usare gli oggetti Q per # 1:

# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
    Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)

I sindacati e le intersezioni, credo, sono un po 'al di fuori dell'ambito del Django ORM, ma è possibile farlo. I seguenti esempi provengono da un'applicazione Django chiamata django-tagging che fornisce la funzionalità. Riga 346 di models.py :

Per la seconda parte, stai cercando un'unione di due query, sostanzialmente

def get_union_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *any* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have any of
    # the given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()

Per la parte # 3 credo che tu stia cercando un incrocio. Vedi riga 307 di models.py

def get_intersection_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *all* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have all the
    # given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s
    HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
        'tag_count': tag_count,
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()

Altri suggerimenti

Li ho testati con Django 1.0:

Il " o " query:

Blog.objects.filter(tags__name__in=['tag1', 'tag2']).distinct()

oppure potresti usare la classe Q:

Blog.objects.filter(Q(tags__name='tag1') | Q(tags__name='tag2')).distinct()

Il " e " query:

Blog.objects.filter(tags__name='tag1').filter(tags__name='tag2')

Non sono sicuro del terzo, probabilmente dovrai passare a SQL per farlo.

Per favore, non reinventare la ruota e utilizzare django-tagging application che era fatto esattamente per il tuo caso d'uso. Può fare tutte le domande che descrivi e molto altro ancora.

Se devi aggiungere campi personalizzati al tuo modello di Tag, puoi anche dare un'occhiata a my branca del django-tagging .

Questo farà al caso tuo

Blog.objects.filter(tags__name__in=['tag1', 'tag2']).annotate(tag_matches=models.Count(tags)).filter(tag_matches=2)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top