Hi,

If you find yourself doing that a lot in your project, yes a custom manager 
is the way to go. Keep in mind that you can more then one manager attached 
to your model, but the order matters 
<https://docs.djangoproject.com/en/1.9/topics/db/managers/#default-managers>. 
For the admin purposes, you can attach the default manager to your model, 
and call it by overriding the get_queryset() ModelAdmin method from here 
<https://github.com/django/django/blob/master/django/contrib/admin/options.py#L318>

# models.py
class Article(models.Model):
   ....
   objects = ExcludeExpiredManager()
   with_expired_objects = models.Manager()

# admin.py
class ArticleAdmin(admin.ModelAdmin):
    
    def get_queryset(self, request):
        qs = self.model.with_expired_objects.get_queryset()        
        ordering = self.get_ordering(request)
        if ordering:
            qs = qs.order_by(*ordering)
        return qs        

On a personal note, I prefer defining custom queryset and use the 
as_manager() 
<https://docs.djangoproject.com/en/1.9/topics/db/managers/#creating-a-manager-with-queryset-methods>
 method 
to get the manager, but in your case you might need the from_queryset() 
<https://docs.djangoproject.com/en/1.9/topics/db/managers/#from-queryset>, 
but I've never used it myself.

Hope that helps

On Tuesday, 12 July 2016 12:54:26 UTC+1, AT wrote:
>
> Being new to Django I wonder if someone could point me in the right 
> direction and I apologise in advance if this is an obvious question.
>
> I have a model with a field that sets an expiry date.
>
> In my ListView I have the following:
> queryset = 
> Article.objects.filter(expiry_date__gt=datetime.now()).order_by('expiry_date')
> Every thing works fine at this point.
>
> Would it be better to include this in a custom manager instead and if so 
> how is this handled in the view or is it done just by including:
> model = Article
>
> A second point is, if I do this will the expired articles still be 
> accessible via the admin?
>
> Many Thanks
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/bcb12d7b-41ad-4de8-8afa-74b3de9d5707%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to