1

I have the following Postgres syntax, that does what I want it to do, however, I would like to implement it in the models.py tab in ORM.

SELECT split_part(booking_inform, ',', 1) AS col1
     , split_part(booking_inform, ',', 2) AS col2
     , split_part(booking_inform, ',', 3) AS col3
     , split_part(booking_inform, ',', 4) AS col4
     , split_part(booking_inform, ',', 5) as col5
     , split_part(booking_inform, ',', 6) as col6

FROM   main_inmate;

I am splitting the column "booking inform" into six new columns based on a commas.

Thanks!

2
  • 2
    Why not store it in six different columns? It will make it harder to update/filter/... if you store it in e column. Commented Nov 15, 2020 at 23:21
  • as Willem already stated it would be better to split it in columns, if you still dont want to do it check docs.djangoproject.com/en/3.1/ref/models/expressions/… Commented Nov 15, 2020 at 23:54

1 Answer 1

2

Here is how your Postgresql query would translate in Django ORM. Assuming your model is named MainInmate.

from django.db.models import Func

class SplitPart(Func):
    function = 'split_part'
    arity = 3

MainInmate.objects.annotate(
   **{f'col{i}': SplitPart(F('booking_inform'), ',', i) for i in range(1, 7)}
).values(*[f'col{i}' for i in range(1, 7)])

However, if you store a list of values in a column, I would rather recommend to use a column of array type, which is available as ArrayField in Django.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Antoine, if I have to also do an average on each of the column post split, what do I need to do additionally? It would be great if you could answer this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.