从文件URL确定模型实例

问题描述

鉴于请求中的URL是针对已知的静态文件,我如何确定哪个模型实例引用了该文件

如果我有几个不同的Django模型,每个模型都有一个ImageField,那么这些字段都知道如何在文件系统上存储相对路径:

# models.py

from django.db import models

class Lorem(models.Model):
    name = models.CharField(max_length=200)
    secret_icon = models.ImageField(upload_to='secrets')
    secret_banner = models.ImageField(upload_to='secrets')

class UserProfile(models.Model):
    user = models.ForeignKey(User)
    secret_image = models.ImageField(upload_to='secrets')

模板可以使用instance.secret_banner.url属性来渲染这些图像。

当收到针对同一URL的请求时,我想在视图中处理该请求:

# urls.py

from django.urls import path

from .views import StaticImageView

urlpatterns = [
    ...,path(settings.MEDIA_URL + 'secrets/<path:relpath>',StaticImageView.as_view(),name='static-image'),]

因此StaticImageView.get方法将通过从URL解析的relpath参数传递。

到那时,我需要根据哪个实例为该静态图片创建URL进行更多处理。

# views.py

from django.views.generic import View

class StaticImageView(View):

    def get(self,request,relpath):
        instance = figure_out_the_model_instance_from_url_relpath(relpath)
        do_more_with(instance)

我不知道该怎么写figure_out_the_model_instance_from_url_relpath代码

如何使用该路径查找生成该URL的模型和实例

解决方法

您可以查询图像文件或从图像文件名获取实例。 首先从relpath获取文件名,然后查询实例。

示例代码示例:

class StaticImageView(View):

    def get(self,request,relpath):
        fname = get_filename_from_relpath(relpath)
        instance = Lorem.objects.get(secret_icon=fname)
        
        do_more_with_instance(instance)

我假设您想基于secret_icon图片来获取图片。您可以根据需要进行更改。