Where to post common requests in Django?

I have a query that is complex enough that I am currently using in one view to get a list of objects.

I want to use the same set of queries in several other views, but would rather just not copy the code several times. I could use a dispatcher to save the request in one place and use it in each view, except that the request depends on a date that is different on each page.

As I understand it, managers do not allow you to pass variables ... so I wonder where I should put this request, so as not to repeat it in multiple views. Any thoughts?

FWIW, this is my request, and publish_date is a variable that changes on every page:

day_publications = Publication.objects.filter(
        Q(reading__end_date__gte=published_date) | Q(reading__end_date__isnull=True),
        reading__start_date__lte=published_date,
).select_related('series',)
+5
source share
1 answer

I think you should use a dispatcher. I usually use these methods in my managers:

class CustomManager(models.Manager):

    def get_records(self, city_slug, dt):
        filter_kwargs = { 
            'city__slug': city_slug,
            'date_from__lt': dt,
            'date_to__gt': dt,
        }   
        return super(CustomManager, self).get_query_set().filter(**filter_kwargs)

Then I run the query in my model:

MyModel.objects.get_records(city.slug, datetime.now())

Of course, you can follow another filter call and bind them or do whatever you want. There is nothing wrong with the approach that managers are here for :-).

+8
source

All Articles