From 9d00d214e1a90837da44a906edfbc40d4c024f52 Mon Sep 17 00:00:00 2001 From: Diederik van der Boor Date: Mon, 22 Jul 2013 10:19:13 +0200 Subject: [PATCH] Fix unwanted `___` handling when a fieldname starts with an underscore. --- docs/changelog.rst | 2 ++ polymorphic/query_translate.py | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 51f8c58..e0faf1d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -5,6 +5,8 @@ Version 0.5.2 (unreleased) -------------------------- * Fix Grappelli_ breadcrumb support in the views. +* Fix unwanted ``___`` handling in the ORM when a field name starts with an underscore; + this detects you meant ``relatedfield__ _underscorefield`` instead of ``ClassName___field``. Version 0.5.1 (2013-07-05) diff --git a/polymorphic/query_translate.py b/polymorphic/query_translate.py index a5f8413..b6ee8cc 100644 --- a/polymorphic/query_translate.py +++ b/polymorphic/query_translate.py @@ -6,7 +6,8 @@ from __future__ import absolute_import from django.db import models from django.contrib.contenttypes.models import ContentType -from django.db.models import Q +from django.db.models import Q, FieldDoesNotExist +from django.db.models.related import RelatedObject from functools import reduce @@ -146,9 +147,21 @@ def translate_polymorphic_field_path(queryset_model, field_path): raise AssertionError(e) else: - # the user has only given us the class name via __ + # the user has only given us the class name via ___ # => select the model from the sub models of the queryset base model + # Test whether it's actually a regular relation__ _fieldname (the field starting with an _) + # so no tripple ClassName___field was intended. + try: + # rel = (field_object, model, direct, m2m) + field = queryset_model._meta.get_field_by_name(classname)[0] + if isinstance(field, RelatedObject): + # Can also test whether the field exists in the related object to avoid ambiguity between + # class names and field names, but that never happens when your class names are in CamelCase. + return field_path # No exception raised, field does exist. + except FieldDoesNotExist: + pass + # function to collect all sub-models, this should be optimized (cached) def add_all_sub_models(model, result): if issubclass(model, models.Model) and model != models.Model: