﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
30631	Prefixing Q Objects.	Robert Schindler	nobody	"I'm currently spending a lot of time on development of a project using Django and worked out something that I think could be of use for all Django users.

I added a new `.prefix(prefix)` method to the `Q` object, allowing to shift pre-built `q` objects to a related field. I think this can change the way people build managers completely, because instead of methods returning filtered querysets, one can just return `Q` objects, which can then be used from related models without repeating the filtering logic.

This is the simple implementation.

{{{
class Q(django.db.models.Q):
    """"""
    A custom Q implementation that allows prefixing existing Q objects with some
    related field name dynamically.
    """"""

    def prefix(self, prefix):
        """"""Recursively copies the Q object, prefixing all lookup keys.

        The prefix and the existing filter key are delimited by the lookup separator __.
        Use this feature to delegate existing query constraints to a related field.
        """"""
        return type(self)(
            *(
                child.prefix(prefix)
                if isinstance(child, Q)
                else (prefix + LOOKUP_SEP + child[0], child[1])
                for child in self.children
            ),
            _connector=self.connector,
            _negated=self.negated,
        )
}}}

What do you think, is it worth creating a PR for this functionality? I haven't written the docs yet, but could write something if you like the addition.

Best regards
Robert
"	New feature	closed	Database layer (models, ORM)	dev	Normal	wontfix	prefix q objects		Unreviewed	1	1	1	0	0	0
