0

I have a method like this:

def build_query(self, ids):
    return '''select   
        d.name as degree,
        fs.student_id
        from form_status fs
        left join form_fills fc
        on fs.id = fc.form_fills_id
        ...
        where fs.student_id in (*ids);
    '''

and ids is a list that looks like this: [1,2,3,100,10000]

How do I do this properly? I like the triple quoted strings because they allow me to indent the sql string and not look weird. Can I maintain this?

Jwan622
  • 11,015
  • 21
  • 88
  • 181

1 Answers1

2

Since tuples in Python happen to be enclosed in parentheses too, you can convert ids to a tuple in an f-string to make the code look aesthetically to your expectation:

def build_query(self, ids):
    return f'''select   
        d.name as degree,
        fs.student_id
        from form_status fs
        left join form_fills fc
        on fs.id = fc.form_fills_id
        ...
        where fs.student_id in {(*ids,)};
    '''
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Why do I need the trailing comma? What is going on here exactly? – Jwan622 Nov 27 '19 at 15:46
  • The trailing comma is syntactically required for a tuple with exactly one item. Please see https://stackoverflow.com/questions/7992559/what-is-the-syntax-rule-for-having-trailing-commas-in-tuple-definitions – blhsing Nov 27 '19 at 16:31