Manager for something like __inall

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class AllInManager(models.Manager):
    """
    Provides the method from_related_ids, which lets you
    select some objects by providing a list of related ids
    (The huge difference to __in is that the objects have 
    to match al of the ids, not only one)
    Model Example::

    class Article(models.Model):
        text = models.TextField()
        tags = ManyToManyField('Tag')
        objects = AllInManager()

    Usage::

    Article.objects.from_related_ids((1,2,3,4), 'tags')
    """
    def from_related_ids(self,id_list, field):
        if len(id_list) == 1:
            mapper = { '%s__in' % field : id_list}
            query = self.model.objects.filter(**mapper)
        else:
            from django.db import connection
            cursor = connection.cursor()

            opts = self.model._meta
            field = opts.get_field(field)
            table = field.m2m_db_table()

            query = """
                SELECT %(field)s FROM %(table)s
                WHERE %(field_reverse)s IN (%(id_list)s)
                GROUP BY %(field)s HAVING COUNT(%(field_reverse)s) = %%s
                    """ % { 'field': field.m2m_column_name(),
                            'field_reverse': field.m2m_reverse_name(),
                            'table': table,
                            'id_list': ','.join(['%s'] * len(id_list))}

            params = [int(i) for i in id_list] + [len(id_list)]

            cursor.execute(query, params)
            erg_ids = cursor.fetchall()
            query = self.model.objects.filter(pk__in=[i[0] for i in erg_ids])
        return query

More like this

  1. sort_by_id_sequence by simon 5 years, 11 months ago
  2. TaggedManager and TaggedQuerySet with chainable tagged() methods implemented with django-tagging by fish2000 4 years, 1 month ago
  3. self-related objects list with links by kumbry 6 years, 5 months ago
  4. RelatedMixin for Details and Updates with Related Object Lists by christhekeele 1 year, 11 months ago
  5. Prefill ForeignKey caches by insin 5 years, 6 months ago

Comments

apollo13 (on November 13, 2007):

There is a huge difference.

tags__in=(1,2,3,4) matches all Articles which tags are 1,2,3 or 4 (If one Article has more than one tag it is okay but not a requirement).

from_related_ids((1,2,3,4),'tags') only matches Articles which are assigned to 1 and 2 and 3 and 4.

#

(Forgotten your password?)