[Fixed]-Building Django Q() objects from other Q() objects, but with relation crossing context

1👍

Maybe someone suggests something better, but I ended up passing the context manually to such functions. I don’t think there is an easy solution, as you might need to call a whole chain of related tables to get to your field, like table1__table2__table3__profile__user__username, how would you guess that? User table could be linked to table2 too, but you don’t need it in this case, so I think you can’t avoid setting the path manually.

Also you can pass a dictionary to Q() and a list or a dictionary to filter() functions which is much easier to work with than using keyword parameters and applying &.

def UsernameStartsWithAaccount(context=''):
    field = 'username__startswith'
    if context:
        field = context + '__' + field
    return Q(**{field: 'a'})

Then if you simply need to AND your conditions you can combine them into a list and pass to filter:

UserProfile.objects.filter(*[startsWithA, wantsEmails])
👤serg

Leave a comment