簡體   English   中英

我想在 Django 中將視圖中的數據操作到/渲染(html)

[英]I would like to manipulate the data from the views to / render (html) in Django

我在 django 中使用泛型有這個視圖,我需要對其進行操作。 但似乎每當我嘗試使用setattr時,它都不會操縱/替換queryset中的數據。

視圖.py

class ArticleListView(ListView): #using the Generic ListView in django
    template_name = 'article/article_list_view.html'
    queryset = Article.objects.all()[:5]

    def get(self, request, *args, **kwargs):
        setattr(self.queryset[0], 'title', 'something') #Trying to change the title in the first element
        print(getattr(self.queryset[0], 'title')) #it outputs the old value
        return super().get(request, *args, **kwargs)

article_list_view.html

{% extends 'base.html' %}

{% block content %}
{% for instance in object_list %}
    <h5>{{instance.title}}</h5>
    {% autoescape off %}                                                                                                                                                                                                                      
        <p>{{instance.content| capfirst}}</p>
    {% endautoescape %}
{% endfor %}
{% endblock content %}

你有什么想法來解決這個問題嗎? 或者可能是因為它是不可變的?

這是一個挑戰,因為根據Django 的關於查詢集的文檔, “可以構建、過濾、切片並通常在不實際訪問數據庫的情況下傳遞查詢集”。 您和我都嘗試的第一件事是從查詢集中獲取第一個 object 並設置屬性。 這無濟於事,因為在您迭代它之前不會評估查詢集本身: {% for instance in object_list %} 發生這種情況時,將再次從數據庫中檢索 model 實例。

我能看到的最佳解決方案是在更新 model 實例之前強制評估查詢集。

class ArticleListView(ListView):
    template_name = 'article/article_list_view.html'
    queryset = Article.objects.all()[:5]

    def get_context_data(self, *, object_list=None, **kwargs):
        # Overwriting this method to receive exactly the same arguments as the original
        # https://github.com/django/django/blob/3.0.6/django/views/generic/list.py#L113
        if object_list is None:
            object_list = self.object_list

        if not isinstance(object_list, tuple):  # Force the queryset into a tuple so it's evaluated
            object_list = tuple(object_list)

        object_list[0].title = 'something'  # Update the instance's title
        return super().get_context_data(object_list=object_list, **kwargs)

除非您在視圖上明確設置context_object_name = 'article_list' ,否則article_list的缺點確實在上下文中不可用,但您已經沒有使用該變量。

我已經測試了部分代碼以驗證我的理論是否正確,但我還沒有完整地運行代碼,因此您可能需要調整一些東西以使其完全按照您的意願工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM