0

I have two models, Sample and Run. A Sample can belong to multiple Runs. The Run model has name that I would like to use to filter Samples on; I would like to find all Samples that have a run with a given name filter. In SqlAlchemy, I write this like:

Sample.query.filter(Sample.runs.any(Run.name.like('%test%'))).all()

In Django, I start with:

Sample.objects.filter(run__in=Run.objects.filter(name__icontains='test'))

or

Sample.objects.filter(run__name__icontains='test')

However both of these produce duplicates so I must add .distinct() to the end.

The Django approach of using distinct has terrible performance when there are a large number of predicates (because the distinct operation must runs over a large number of possible rows) whereas the SqlAlchemy runs fine. The repeated rows come from repeated left outer join from each predicate.

For example:

Sample.objects.filter(Q(**{'run__name__icontains': 'alex'}) |
     Q(**{'run__name__icontains': 'baz'}) | ...)

EDIT: To make this a little more complicated, I do want the ability to have filters like:

(Q(**{'run__name__icontains': 'alex'}) | Q(**{'name__icontains': 'alex'})
  & Q(**{'run__name__icontains': 'baz'}) | Q(**{'name__icontains': 'baz'}))

which has a SQLAlchemy query like:

clause1 = Sample.runs.any(Run.name.like('%alex%')) | Sample.name.like('%test%')
clause2 = Sample.runs.any(Run.name.like('%baz%')) | Sample.name.like('%baz%')
Sample.query.filter(clause1 & clause2)

1 Answer 1

0

Assuming this is your models.py:

from django.db import models

class Sample(models.Model):
    name = models.CharField(max_length=255)

class Run(models.Model):
    name = models.CharField(max_length=255)
    sample = models.ForeignKey(Sample)

Since I wasn't able to figure out how to do this without using "distinct", or without using "raw" (in which, if you're forming your own SQL code, and can't rely on the ORM, then what's the point :p), I recommend to try replacing the Django ORM with SQLAlchemy, or use them along-side each other, since theoretically that would work. Sorry I couldn't be of much help :(

Here is a fairly-recent blog post that can help you do that: http://rodic.fr/blog/sqlalchemy-django/

7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.