Application configuration classes

Django allows you to specify configuration classes for your applications. When you create an application using the startapp command, Django adds an apps.py file to the app directory, including a basic app configuration that inherits from the AppConfig class.

The application configuration class allows you to store metadata and configuration for the application and provides introspection for the app. You can find more information about application configurations at https://docs.djangoproject.com/en/2.0/ref/applications/.

In order to register your signal receiver functions, when you use the receiver() decorator, you just need to import the signals module of your application inside the ready() method of the application configuration class. This method is called as soon as the application registry is fully populated. Any other initializations for your application should also be included in this method.

Edit the apps.py file of the images application and make it look like this:

from django.apps import AppConfig

class ImagesConfig(AppConfig):
name = 'images'

def ready(self):
# import signal handlers
import images.signals

We import the signals for this application in the ready() method so that they are imported when the images application is loaded.

Run the development server with the following command:

python manage.py runserver

Open your browser to view an image detail page and click on the LIKE button. Go back to the administration site, navigate to the edit image URL, such as http://127.0.0.1:8000/admin/images/image/1/change/, and take a look at the total_likes attribute. You should see that the total_likes attribute is updated with the total number of users that like the image, as follows:

Now, you can use the total_likes attribute to order images by popularity or display the value anywhere, avoiding complex queries to calculate it. Consider the following query to get images ordered according to their like count:

from django.db.models import Count

images_by_popularity = Image.objects.annotate(
likes=Count('users_like')).order_by('-likes')

The preceding query can now be written as follows:

images_by_popularity = Image.objects.order_by('-total_likes')

This results in a less expensive SQL query. This is just an example of how to use Django signals.

Use signals with caution since they make it difficult to know the control flow. In many cases, you can avoid using signals if you know which receivers need to be notified.

You will need to set initial counts to match the current status of the database. Open the shell with the python manage.py shell command and run the following code:

from images.models import Image
for image in Image.objects.all():
image.total_likes = image.users_like.count()
image.save()

The likes count for each image is now up to date.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset