A Nice Django Long Queries Style

106 views
Skip to first unread message

Lee

unread,
Feb 2, 2017, 8:27:44 PM2/2/17
to Django developers (Contributions to Django itself)
If your django queries is too long (>100 character), you can try this style

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

In this style, the most convenience is you do not have to indent by hand, every line indent is several 4 spaces.

Disadvantage of the below: 1. If you rename the variable person, you have to adjust indent by hand. 2. If your model name is very long, it is difficult to limit every line less than 80 characters.

person = UzbekistaniCitizen.objects.myfilter(hair__color=brown,
                                            eye__color= blue,
                                            height__gt= 56,
                                            ...
                                            ...
                                            )

My style have other convenience:

1.can add comment:

person = (
    models
    .UzbekistaniCitizen
    .objects
    .filter(occupation__income__taxable__gte=40000)  # your comment
    .exclude(face__eyes__color=blue)
    .order_by('height')  # 2016-10-11 add
    .select_related('siblings', 'children')
)

2.easy debug, you can comment some conditions easily

Below code can work fine. This is very useful in debug, you can comment condition line-by-line, rather than delete it and redo it.

person = (
    models
    .UzbekistaniCitizen
    .objects
    # .filter(occupation__income__taxable__gte=40000)
    .exclude(face__eyes__color=blue)
    # .order_by('height')
    .select_related('siblings', 'children')
)
Reply all
Reply to author
Forward
0 new messages