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')
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
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.
#
Please login first before commenting.