📜  django router multiple pk - Python (1)

📅  最后修改于: 2023-12-03 15:30:29.153000             🧑  作者: Mango

Django Router Multiple PK

When working with Django and creating dynamic URLs, it is common to need to handle multiple primary keys (PKs) in a single URL. For example, you may have a web application with a database of products, each of which is associated with a certain category and manufacturer.

To properly handle these types of URLs, Django provides a router system that allows you to map URLs to views using regular expression patterns. In this tutorial, we will explore how to use the Django router to handle multiple PKs in a URL.

Creating a Project

To get started, make sure you have Django installed. You can do this by running the following command:

pip install django

Once Django is installed, create a new project by running the following command:

django-admin startproject myproject

This will create a new directory called myproject that contains the basic files needed for a Django project.

Creating an App

Next, create a new app by running the following command:

cd myproject
python manage.py startapp myapp

This will create a new directory called myapp within the myproject directory.

Defining the Model

To keep things simple, we will use a basic model for our example. Open the models.py file in your myapp directory and add the following code:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Manufacturer(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

This defines a basic model with three components: Category, Manufacturer, and Product. Each Product is associated with a certain Category and Manufacturer.

Defining the Router

Next, we need to define a router to handle the URLs that we will be using for our web application. In your myapp directory, create a new file called urls.py and add the following code:

from django.urls import path
from . import views

urlpatterns = [
    path('products/<int:category_id>/<int:manufacturer_id>/', views.products_by_category_and_manufacturer),
]

This defines a single URL pattern with two integer parameters: category_id and manufacturer_id. These two values will be used to filter the Product objects in our view.

Defining the View

With our router defined, we can now define the view that will be called when a user accesses the URL that we have defined. In your views.py file, add the following code:

from django.shortcuts import render
from .models import Product

def products_by_category_and_manufacturer(request, category_id, manufacturer_id):
    products = Product.objects.filter(category_id=category_id, manufacturer_id=manufacturer_id)
    context = {
        'products': products
    }
    return render(request, 'products.html', context)

This view uses the Product.objects.filter() method to retrieve all Product objects that match the category_id and manufacturer_id parameters that were passed in the URL. These objects are then returned in a dictionary as the products key.

Defining the Template

Finally, we need to define the HTML template that will be used to display the Product objects returned by our view. In your myapp directory, create a new directory called templates. Within that directory, create another directory called myapp. Within the myapp directory, create a new file called products.html and add the following code:

{% extends 'base.html' %}

{% block content %}
<h1>Products</h1>
<ul>
{% for product in products %}
    <li>{{ product.name }}</li>
{% empty %}
    <li>No products to display</li>
{% endfor %}
</ul>
{% endblock %}

This defines a template that extends a base template (which we haven't defined yet). It displays a list of all Product objects that were returned by our view.

Running the Application

To run our application, start the Django development server by running the following command:

python manage.py runserver

Then, navigate to http://localhost:8000/products/1/1/ in your web browser. You should see a list of all Product objects that have a Category ID of 1 and a Manufacturer ID of 1.

Conclusion

In this tutorial, we explored how to use the Django router system to handle multiple primary keys in a single URL. We defined a router to map a URL to a view, defined a view to query the database and return the desired objects, and defined a template to display those objects to the user. By following these steps and customizing them to fit your specific needs, you can create robust and dynamic web applications using Django.