英文:
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's filtracking via [prefetch_related][1], which should limit it to two DB calls
   
    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"
        )
    )
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't actually mentioned in the model fields you provide. I've assumed it's in there somewhere. 
  [1]: https://docs.djangoproject.com/en/4.2/ref/models/querysets/#prefetch-related
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论