Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Style: Long queries?

I have some rather long (~150 character) django queries. What's the preferred way to split them onto multiple lines?

For example (no, not my real code):

Edit: Changed the example because people were focused on repeating filter, not the length of the query:

person = models.UzbekistaniCitizen.objects.filter(occupation__income__taxable__gte=40000).exclude(face__eyes__color=blue).order_by('height').select_related('siblings', 'children') 

Here are two ways I can think of:

  1. Use backslashes as line breaks:

    person = models.UzbekistaniCitizen.objects.\                           filter(occupation__income__taxable__gte=40000).\                           exclude(face__eyes__color=blue).\                           order_by('height').\                           select_related('siblings', 'children') 
  2. Re-apply the filter in new lines:

    person = models.UzbekistaniCitizen.objects person = person.(occupation__income__taxable__gte=40000) person = person.exclude(face__eyes__color=blue) person = person.order_by('height') person = person.select_related('siblings', 'children') 
like image 423
spencer nelson Avatar asked Oct 28 '11 17:10

spencer nelson


1 Answers

You can use parentheses around the whole rhs to get implied line continuation:

person = (models.UzbekistaniCitizen                 .objects                 .filter(occupation__income__taxable__gte=40000)                 .exclude(face__eyes__color=blue)                 .order_by('height')                 .select_related('siblings', 'children')) 
like image 109
Sean Avatar answered Sep 23 '22 12:09

Sean