Django Custom Models

38 views
Skip to first unread message

AT

unread,
Jul 12, 2016, 11:54:26 AM7/12/16
to Django users
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

Bruno A.

unread,
Jul 13, 2016, 8:18:35 AM7/13/16
to Django users
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. 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

# 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() method to get the manager, but in your case you might need the from_queryset(), but I've never used it myself.

Hope that helps

AT

unread,
Jul 14, 2016, 11:33:04 AM7/14/16
to django...@googlegroups.com
Thanks for this. Now everything makes perfect sense.
Reply all
Reply to author
Forward
0 new messages