[Answer]-Django queryset flipping

1πŸ‘

Such as turning a Foo queryset into a Bar queryset if all Foo objects have a foreign key to Bar?

Why not? Here’s one approach, if you always write the base query as the one local to the object in question.

bar_query = {
   'something': 'something',
}

def prefix_fk(query, prefix):
    prefixed_query = {}
    for key, value in query.items():
        prefixed_query[prefix+key] = value
    return prefixed_query

Foo.objects.filter(**prefix_fk(bar_query, 'bar__'))
Bar.objects.filter(**bar_query)

if condition_2:
    bar_query['another_query'] = 'foobar'
    Foo.objects.filter(**prefix_fk(bar_query, 'bar__'))
    Bar.objects.filter(**bar_query)

Leave a comment