在Django模板中显示属性筛选值

huangapple go评论64阅读模式
英文:

Showing property filter value in Django template

问题

I couldn't get the value of the LastActiveTrack in my template. Any ideas?

在我的模板中,我无法获取LastActiveTrack的值。有什么想法吗?

英文:

I have the follwoing models in my Django project:

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)
    ...

my view:

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

In my template, I want to show the description or title of the last active record.

I tried to create a property in the FileTracking model:

@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 ''

in my template:

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

but I couldn't get the value of the LastActiveTrack in my template. Any ideas?

答案1

得分: 0

在模板中这样做不太理想,因为你会为每个文件进行一次数据库调用,如果文件很多,这可能会导致不必要的开销。

更好的方法是更新你的初始调用,包括每个文件的文件跟踪信息,可以使用prefetch_related来实现,这应该限制为两次数据库调用。

current_files = files.filter(...).prefetch_related(
    Prefetch(
        'file_tracking', 
        queryset=FileTracking.objects.order_by("-date"),
        # 为了在模板中明确引用,可以在Prefetch中添加一个to_attr参数
        to_attr="filetrack_ordered"
    )
)

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

{% for file in current_files %}
    Title: {{file.title}}
    Last Tracking: {{file.filetrack_ordered.0.title}}
{% endfor %}

注意:在你的问题中,似乎你正在寻找file_tracking.title,但在你提供的模型字段中并没有实际提到。我假设它在模型中的某个地方。


<details>
<summary>英文:</summary>

Doing this in your template is less than ideal as you will make a database call for each file, which may get expensive in overhead if you have a lot of files.

Better to update your initial call to include each file&#39;s filtracking via [prefetch_related][1], which should limit it to two DB calls
   
    current_files = files.filter(...).prefetch_related(
        Prefetch(
            &#39;file_tracking&#39;, 
            queryset=FileTracking.objects.order_by(&quot;-date&quot;),
            #to make it clear what we are referring to in our template
            #add a to_attr argument to Prefetch
            to_attr=&quot;filetrack_ordered&quot;
        )
    )

then in your template you can call:

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

NB: in your question you seem to be looking for file_tracking.title which isn&#39;t actually mentioned in the model fields you provide. I&#39;ve assumed it&#39;s in there somewhere. 

  [1]: https://docs.djangoproject.com/en/4.2/ref/models/querysets/#prefetch-related

</details>



huangapple
  • 本文由 发表于 2023年5月14日 09:34:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定