79496717

Date: 2025-03-09 22:44:06
Score: 0.5
Natty:
Report link

Common table expressions aren't really supported natively by the the ORM, so you might be looking at a cursor situation to execute some plain old sql (https://docs.djangoproject.com/en/5.1/topics/db/sql/#executing-custom-sql-directly).

Not sure if you are using postgres or another relational database but CTEs should probably be similar between them https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-MODIFYING.

You would maybe end up with something like:

with connection.cursor() as cursor:
    cursor.execute(
    """
    WITH insertedArticles AS (
        INSERT INTO articles
            (name, subtitle) 
        VALUES
            ('name_value', 'subtitle_value')
        RETURNING article_id
    )
    INSERT INTO comments
        (article_id, comment_text)
    SELECT
        insertedArticles.article_id, $1
    FROM insertedArticles;

    """

As always with using raw sql rather than ORM methods, make sure to parameterize inputs.

Reasons:
  • Blacklisted phrase (1): TO comment
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: twrought