Where to put common queries in Django?

浪尽此生 提交于 2021-02-07 13:22:54

问题


I have a queryset that is reasonably complicated, which I currently use in a single view for getting a list of objects.

I want to use the same queryset in a couple of other views but would prefer not to just copy the code multiple times. I could use a Manager, to keep the queryset in one place, and use that in each view except the query relies on a date which is different on each page.

As I understand it, Managers don't let you pass in variables... so I'm wondering where I should put this query so as not to keep repeating it in several views. Any thoughts?

FWIW, this is my queryset, and published_date is the variable that changes on each 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',)

回答1:


I think you should actually use a Manager. I habitually use methods like this 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 on my model:

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

Of course, you can follow up with another call of filter and chain these or do whatever you want. There's nothing wrong with this kind of approach, that's what managers are here for :-).



来源:https://stackoverflow.com/questions/4541780/where-to-put-common-queries-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!