How to be more DRY in the view code ?

Hi,
I would like to find a way to write the view code in a more DRY way.
Here is my problematic:
Let say for example, I have an index.html with this view :

def index(request):
    some_data = QuerySet()

    return render(request, 'index.html', {
        'some_data': some_data,
    })

Now I {% extands %} the the first index.html in another page : “my_second_page.html”
and I need the data from the index.html too + some other data. I need to write this:

def my_second_page(request):
    some_data = QuerySet()
    other_data =  QuerySet()

    return render(request, 'my_second_page.html', {
        'some_data': some_data,
        'other_data': other_data,
    })

If I’m not mistaking, I need to declare in every view the data I want, even if it was the same QuerySet from another view, but this is not DRY at all.
So what is the best approach to be more DRY ? class ?

While I wouldn’t worry about creating QuerySets in each view, if you really wanted to avoid that type of duplication (which I personally don’t think is an issue needing to be addressed) you could do something like this:

def get_some_data_queryset():
    return QuerySet()

def index(request):
    return render(request, 'index.html', {'some_data': get_some_data_queryset()})

def my_second_page(request):
    some_data = get_some_data_queryset()
    other_data =  QuerySet()

    return render(request, 'my_second_page.html', {
        'some_data': some_data,
        'other_data': other_data,
    })

but this seems a bit much to me.

Yes, you could reorganize your code into classes such that your second page inherits from and extends your first page.

But unless this is a greatly simplified version of you’re really needing to do and that there’s a lot more involved than what you’re showing here, I would call either type of refactoring to be premature and unnecessary.

1 Like

Sure, this was just an example, my project is more complicate.
OK, thanks, this helped me.

In order to DRY myself, here are the steps I usually take:

  1. Move querysets to models.py whenever I can (i.e., when they refer to the same Model entity)
  2. Switch to class base views
  3. Move repeated code into mixins for the CBVs to inherit

For function-based view I don’t believe there are many options other than extracting functions, like @KenWhitesell mentioned.

2 Likes