简体   繁体   中英

Django/Postgres: in a query with a conditional annotation, return an ArrayField with a certain value in it?

I am using Python 2.7, Postgres 9.6 and Django 1.11. I have a model, Person , with two CharField s on it, director_id and company_id . I'd like to annotate it according to a certain condition: when director_id is not null, do a subquery performing an ArrayAgg that gives me back an array of the company_id s associated with it (fine, got that working); when it is not I'd like to return an array of length 1 simply containing the company_id for this Person . Is there a way to specify that I want default to give back an array with a certain value in it?

Person.objects.annotate(
    aggregated_company_ids=Case(
        When(director_id__isnull=False, then=Subquery(aggregated_company_ids)),
        default=[F("company_id")],  # ProgrammingError: can't adapt type 'F'
        output_field=ArrayField(models.CharField()),
    ),
)

I found ArrayAgg(F("company_id")) worked and gave me an array of with just the one company_id in it:

Person.objects.annotate(
    aggregated_company_ids=Case(
        When(director_id__isnull=False, then=Subquery(aggregated_company_ids)),
        default=ArrayAgg(F("company_id")),
        output_field=ArrayField(models.CharField()),
    ),
)

Not sure whether this is the only and best solution but it's the only one I've found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM