jsm1th
jsm1th

Reputation: 489

Django Query Best Practice

Wondering about some Django querying performance/best practices. It is my understanding that QuerySets are "lazy" as the documentation states and that the three queries below do not run until they are actually evaluated at some point. Is that a correct understanding and is the below snippet a reasonable way to query against the same table for three different filter values against the same field?

    # General Education
    general_education_assignments = FTEAssignment.objects.filter(
        group_name='General Education'
    )
    # Specials
    specials_assignments = FTEAssignment.objects.filter(
        group_name='Specials'
    )
    # Dual
    dual_assignments = FTEAssignment.objects.filter(
        group_name='Dual Language'
    )

Even more so what I am wondering about besides if my understanding of the above is correct is if the below is in anyway more efficient (I don't think it will be)? Also, if either the above or below is better stylistically for Django or more 'pythonic'?

    # Get all assignments then filter
    fte_assignments = FTEAssignment.objects.all()
    # General Education
    general_education_assignments = fte_assignments.filter(
        group_name='General Education')
    # Specials
    specials_assignments = fte_assignments.filter(group_name='Specials')
    # Dual
    dual_assignments = fte_assignments.filter(group_name='Dual Language')

Thank you!

Upvotes: 0

Views: 1007

Answers (1)

SMX
SMX

Reputation: 1442

Your understanding here is correct. The second example works identically in terms of performance and what's happening "under the hood". Often, you'll see code structured like your second example when you're chaining together many filters and exclusions and don't want to repeat yourself. For simple queries, though, your first example is what you'd normally see stylistically.

Upvotes: 2

Related Questions