[Answered ]-Django TextField (CharField) in OuterRef to list with filter _in

1👍

When using OuterRef and Subquery, instead of trying to convert OuterRef to a string, create an OuterRef for the related field and use it directly in the subquery. Then, obtain the related values and use them in a __in lookup. This approach allows you to filter based on a list of strings from facebook_ad_accounts:

facebook_ad_account_outer_ref = OuterRef('facebook_ad_accounts')

spend_subquery = FacebookStatistic.objects.filter(
    ad_account__id_ad=facebook_ad_account_outer_ref
).annotate(
    spd=Coalesce(Func('spend', function='Sum'), 0, output_field=FloatField())
).values('spd')

facebook_ad_account_ids = UserAccount.objects.filter(
    groups__name__contains=group
).values_list('facebook_ad_accounts', flat=True)

user_accounts = UserAccount.objects.filter(
    groups__name__contains=group
).annotate(
    spend=Cast(Subquery(spend_subquery), output_field=FloatField())
)

This approach correctly filters and handles related data in a concise manner.

Leave a comment