Login

Tag "q"

Snippet List

Query lookups using operators

This class emulates query lookups to behave as numeric operators. Inspired by SQLAlchemy. User.objects.filter( X('username') == 'diverman' ) User.objects.filter( X('username') != 'diverman' ) User.objects.filter( X('pk') > 10 ) User.objects.filter( X('pk') >= 10 ) User.objects.filter( X('pk') < 10 ) User.objects.filter( X('pk') <= 10 ) User.objects.filter( X('username') % 'iverma' ) User.objects.filter( X('username') << 'diver' ) User.objects.filter( X('username') >> 'man' ) User.objects.filter( X('pk') | (1, 2, 3) )

  • q
  • query
  • lookup
  • operator
Read More

superSearch function for generating large OR queries

superSearch is intended to make it easier to make complex OR queries, thusly hitting the database less. EXAMPLE: Searching for a user named 'Eric Neuman' would be difficult because first_name and last_name are separate fields. However, with superSearch, it's a breeze. query = ['Eric Neuman'] f = ['first_name','last_name'] s = query.split(' ') m = ['icontains'] results = superSearch(User, f, m,s)

  • dynamic
  • q
  • query
  • kwargs
Read More

CustomQueryManager

A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(query=blah) Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries. `CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so: class MyManager(CustomQueryManager): query = Q(some=query) Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY. Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so: class MyModel(models.Model): field1 = models.CharField(maxlength=100) field2 = models.PositiveIntegerField() my_mgr = CustomQueryManager(Q(field1='Hello, World')) This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example: class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() public = models.BooleanField() confirmed = models.BooleanField() public_bookings = CustomQueryManager(Q(public=True)) private_bookings = public_bookings.not_() confirmed_bookings = CustomQueryManager(Q(confirmed=True)) public_confirmed = public_bookings & confirmed_bookings public_unconfirmed = public_bookings & confirmed_bookings.not_() public_or_confirmed = public_bookings | confirmed_bookings public_past = public_bookings & Q(end_date__lt=models.LazyDate()) public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate()) public_future = public_bookings & Q(start_date__gt=models.LazyDate()) As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.

  • models
  • q
  • manager
  • query
  • custom
Read More

Q marshaller

Django supports the serializing model objects, but does not support the serializing Q object like that, ============================ q = Q(username__contains="findme") model0.objects.filter(q) serialize(q) # X ============================ so I wrote a little marshaller for Q, this is example, ============================ from django.contrib.auth import models as django_models qs = django_query.Q(username__contains="spike") | django_query.Q(email__contains="spike") _m = QMarshaller() a = _m.dumps(qs) # a was serialized. When call the similiar queries in page by page, you don't need to write additional code for creating same Q(s) for filtering models, just use the serialized Q as http querystring and in the next page unserialize and apply it. That is simple life.

  • model
  • python
  • q
  • query
Read More

QLeftOuterJoins

This hack replaces all INNER JOINs inside to the LEFT OUTER JOINs (see http://code.djangoproject.com/ticket/3592 for explanation). Use: QLeftOuterJoins(Q(...) | Q(...) & (Q(...) | ....)).

  • q
  • query
  • join
  • left
  • outer
Read More

QEmpty

Q() value in Django is identity for & operation: Q() & foo & bar & ... == foo & bar & ... QEmpty() is complimentary identity for | operation: QEmpty() | foo | bar | ... == foo | bar | ... QEmpty() itself returns empty queryset. Handy for complex query generation.

  • q
  • query
Read More

Left Outer join Q object

QLeftOuterJoin object allows you to create 'LEFT OUTER JOIN' sql query. It is very usefull if you have to define ForeignKey to 'null=True' (select_related will not work with null=True). You are allowed to use QLeftOuterJoin like Q object. Example: `QLeftOuterJoin('thread_last_post', Post, 'pk', Thread, 'last_post')` It will generates SQL like: LEFT OUTER JOIN appname_post AS thread_last_post ON thread_last_post.id = appname_thread.last_post_id Table could be model or string.

  • sql
  • q
  • query
  • join
Read More

Filter on Multiple M2M Objects Simultaneously

This snippet should allow you to do queries not before possible using Django's ORM. It allows you to "Split" up the m2m object you are filtering on. This is best described by example: Suppose you have `Article` and `Tag`, where `Article` has a m2m relation with `Tag` (`related_name = 'tag'`). If I run: from django.db.models.query import Q Article.objects.filter(Q(tag__value = 'A') & Q(tag__value = 'B')) > # no results I would expect to get no results (there are no tags with both a value of 'A' and 'B'). However, I *would* like to somehow get a list of articles with tags meeting that criteria. Using this snippet, you can: from django.db.models.query import Q from path.to.qsplit import QSplit Article.objects.filter(QSplit(Q(tag__value = 'A')) & QSplit(Q(tag__value = 'B'))) > # articles with both tags So now they are split into different `Tag` entries. Notice how the `QSplit()` constructor takes a `Q` object---it's possible to give this any complicated Q-type expression.

  • models
  • q
  • m2m
  • db
  • orm
Read More

9 snippets posted so far.