Matthew Lemon

Practical Django

Setting up Django

There are plenty of things you need to do.

First off.

QuerySets and Managers

All models get an object manager by default, allowing you to get objects like this:

1
Model.objects.all()

A QuerySet is returned as a result.

To implement a custom manager, so that you can write, for example:

1
Model.published.all()

You can add a subclass to models.Manager in your models.py file:

1
2
3
4
5
class PublishedManger(models.Manager):
    def get_queryset(self):
        return super(PublishedManger, self).get_queryset().filter(status='published')
    ...
    published = PublishedManger()

Filters can be used, e.g:

1
`Model.objects.filter(publish__year=2016).

You use field lookup methods using underscore underscore. This can also be used to access fields of related models.

They can be filtered like this:

1
Model.objects.filter(publish__year=2016).filter(auther__firstname=="Wendell")

Excluding:

1
Model.objects.filter(publish__year=2016).exclude(title__startswith='Knockers')

Ordering (ascending):

1
Model.objects.order_by(publish__year)

Ordering (descending):

1
Model.objects.order_by(-publish__year)

Django QuerySets are lazy.

URL namespaces

Add namespace='blog' in the include() function within urlpatterns in the project-level urls.py file.

Enabled Administration site

Add admin.site.register(Post) to admin.py if you want the default. To amend it, you have to subclass:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish', 'status')
    list_filter = ('status', 'created', 'publish', 'author')
    search_fields = ('title', 'body')
    prepopulated_fields = {'slug': ('title',)}
    raw_id_fields = ('author',)
    date_hierarchy = 'publish'
    ordering = ['status', 'publish']


admin.site.register(Post, PostAdmin)