![]() |
In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you through creating a small Django project that demonstrates how to perform GROUP BY queries. How to Query as GROUP BY in Django?We’ll create a Django project named myproject and an app called myapp. The project will display data grouped by a specific field, mimicking a GROUP BY query in SQL. Step 1: Setting Up the Django ProjectFirst, ensure you have Django installed. If not, install it using pip: pip install django Create a new Django project: django-admin startproject myproject Create a new Django app: python manage.py startapp myapp Add the app to your project’s settings. Open myproject/settings.py and add ‘myapp’ to INSTALLED_APPS: INSTALLED_APPS = [ ![]() Step 2: Creating ModelsLet’s create a model to represent some data we want to group by. In myapp/models.py, define a simple model with a field to group by and another field to aggregate.
Run the following commands to create and apply migrations: python manage.py makemigrations Step 3: Adding Sample DataFor demonstration purposes, add some sample data. You can use the Django admin interface for this. First, create an admin user: python manage.py createsuperuser ![]() Then, register the Item model in myapp/admin.py:
Run the development server and add sample data through the admin interface: python manage.py runserver Step 4: Creating Views and URLsCreate a view to perform the GROUP BY query and display the results. In myapp/views.py, add the following code:
Create a template to display the grouped data. In myapp/templates/grouped_items.html, add the following code:
Set up the URL routing for this view. In myapp/urls.py, add the following code:
Include this app’s URLs in the project’s URL configuration. Edit myproject/urls.py:
Step 5: Running the ServerRun the development server to test your project: python manage.py runserver Visit http://127.0.0.1:8000/grouped/ in your browser. You should see a list of items grouped by category, displaying the total value for each category. ![]() |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |