在 Django 模板中显示属性过滤器值

问题描述 投票:0回答:1

我的 Django 项目中有以下模型:

class File(models.Model):
  client = models.ForeignKey(User, on_delete=models.PROTECT, related_name='client_files')
  title = models.CharField(max_length=250, blank=True, null=True)
  ...
class FileTracking(models.Model):
    file = models.ForeignKey(File, related_name='file_tracking', on_delete=models.CASCADE)
    description = models.CharField(max_length=250, null=True, blank=True)
    title = models.CharField(max_length=250, blank=True, null=True)
    date = models.DateField(auto_now=False, auto_now_add=False)
    active =  models.BooleanField(default=False)
    ...

我的观点:

class FileCurrentView(ListView):
    model = File
    template_name = 'files_current.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            user=self.request.user
            current_files = files.filter(...)
            ...
            context["user"] = user
            context["current_files"]= current_files
            ...
        return context

在我的模板中,我想显示最后一条活动记录的描述或标题。

我尝试在

FileTracking
模型中创建一个属性:

@property
def LastActiveTrack(self):
    result  = self.objects.filter(active=1).order_by("-date")[0].title
    result_txt = str(result)
    if result:            
        return result_txt
    return ''

在我的模板中:

{% for file in current_files %}
    Title: {{file.title}}
    last Tracking: {{file.file_tracking.LastActiveTrack}}
{% endif %}

但是我无法在我的模板中获取

LastActiveTrack
的值。有什么想法吗?

django django-views django-templates django-filter django-template-filters
1个回答
0
投票

在您的模板中执行此操作并不理想,因为您将为每个文件调用数据库,如果您有很多文件,这可能会导致开销很大。

最好更新您的初始调用以通过 prefetch_related 包含每个文件的过滤跟踪,这应该将其限制为两次 DB 调用

current_files = files.filter(...).prefetch_related(
    Prefetch(
        'file_tracking', 
        queryset=FileTracking.objects.order_by("-date"),
        #to make it clear what we are referring to in our template
        #add a to_attr argument to Prefetch
        to_attr="filetrack_ordered"
    )
)

然后在你的模板中你可以调用:

{% for file in current_files %}
    Title: {{file.title}}
    last Tracking: {{file.filetrack_ordered.0.title}}
{% endif %}

NB:在您的问题中,您似乎正在寻找 file_tracking.title ,您提供的模型字段中实际上并未提及。我以为它在某处。

© www.soinside.com 2019 - 2024. All rights reserved.