Django изменяет значения набора запросов перед отображением в шаблоне - PullRequest
0 голосов
/ 03 апреля 2019

У меня есть FormView, который отправляет данные в ListView.
. В LisView я получаю данные с помощью self.request.GET и, используя фильтр qustom, я получаю необходимый набор запросов.Теперь мне нужно изменить некоторые значения в наборе запросов, но я не могу найти, как это сделать.

Попытался индексировать квест в ListView с помощью queriset['name'] или queryset[1], но он говорит мне, что индексне поддерживается.
Пытался применить queryset.values_list() и queriset.values(), а затем индексировать, но результат тот же.
Пытался создать функцию в ListView и применить в шаблоне, получив 'Не удалось разобрать напоминание'.
Наконец, попытался переопределить значения в шаблоне, выполнив object.value - request.GET.value, но я получил эту ошибку:
Could not parse the remainder: ' - request.GET.salary' from 'item.smg70 - request.GET.salary'

views.py

class QuoteListView(ListView):
    model = SmgQuotesTable

    def get_queryset(self):
        r_get = self.request.GET
        d_get = {'name': None , 'email':None , 'couple': None, 'age': None, 'kids':None , 'salary':None}

        for value in d_get:
            d_get[value] = r_get[value]

        query_filter = Quotes().planSelector(d_get['couple'], d_get['kids'], d_get['age'])
        queryset = super(QuoteListView, self).get_queryset().filter(composite=query_filter)

        for i in queryset[1:]:
            i - d_get['salary']
            print(i)


        return queryset


    def salary(self, x):
        salary_get = self.request.GET('salary')

        return x - salary_get

smgquotestable_list.html

{% for item in object_list %}
<div class="table-responsive text-nowrap"></div>
  <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col"></th>
          <th scope="col">SMG01</th>
          <th scope="col">SMG02</th>
          <th scope="col">SMG10</th>
          <th scope="col">SMG20</th>
          <th scope="col">SMG30</th>
          <th scope="col">SMG40</th>
          <th scope="col">SMG50</th>
          <th scope="col">SMG60</th>
          <th scope="col">SMG70</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">{{ item.composite }}</th>
          <td>$ {{ item.smg01 }}</td>
          <td>$ {{ item.smg02 }}</td>
          <td>$ {{ item.smg10 }}</td>
          <td>$ {{ item.smg20 }}</td>
          <td>$ {{ item.smg30 }}</td>
          <td>$ {{ item.smg40 }}</td>
          <td>$ {{ item.smg50 }}</td>
          <td>$ {{ item.smg60 }}</td>
          <td>$ {{ item.smg70 }}</td>
        </tr>
      </tbody>
  </table>
</div>
{% endfor %}

Мне нужно перевести значение заработной платы, отправленное формой, в значения smg01 и т. Д., Которые я получаю вQuerySet.

Ответы [ 3 ]

0 голосов
/ 03 апреля 2019

Вы не делитесь несколькими вещами, такими как поля модели для SmgQuotesTable или ваш код для Quote и planSelector. Но, предполагая, что вы пытаетесь отфильтровать результат, используя значения, которые вы получаете в своем объекте self.request (например, значения для имени, адреса электронной почты, пары и т. Д.), И предполагая, что это на самом деле поля для вашего SmgQuotesTable, вам следует пойти по этому обычному пути (см. документы ). Также обратите внимание, что вам не нужно вызывать Super в get_queryset. Вы можете спутать это с get_context_data

, который вам нужно будет назвать super, чтобы получить контекст.

class QuoteListView(ListView):
    model = SmgQuotesTable

    def get_queryset(self):
        r_get = self.request.GET
        d_get = {'name': None , 'email':None , 'couple': None, 'age': None, 'kids':None , 'salary':None}

        for value in d_get:
            d_get[value] = r_get[value]  # I do NOT know what you are doing here, so I am going by your code

        filtered_quotes = SmgQuotesTable.objects.filter(**d_get)

        return filtered_quotes
0 голосов
/ 03 апреля 2019

Моя ошибка заключалась в недооценке, как сказал мне Диркгротен, что я являюсь экземпляром объекта.Поэтому мне нужно сделать i.value, чтобы использовать доступ к значениям.

Вот что я решаю:

В quotes.py я пишу функцию под названием salaryDiscount, которая изменяет значения на ходу:

    def salaryDiscount(self, queryset, salary):
        '''
        This function apply the salary discount to all the values for this person. 
        '''
        salary = float(salary) * 0.03  # Take the salary, and aply the part that could be discounted

        for i in queryset:  # Get the object of the queryset
            i.smg01 = round(i.smg01  - salary, 2)    # Use the object edit the values on the fly
            i.smg02 = round(i.smg02  - salary, 2)
            i.smg10 = round(i.smg10  - salary, 2)
            i.smg20 = round(i.smg20  - salary, 2)
            i.smg30 = round(i.smg30  - salary, 2)
            i.smg40 = round(i.smg40  - salary, 2)
            i.smg50 = round(i.smg50  - salary, 2)
            i.smg60 = round(i.smg60  - salary, 2)
            i.smg70 = round(i.smg70  - salary, 2)

        return queryset   # Return the queryset edited. 

Затем я вызываюэто на get_queryset из ListView, где изменить набор запросов:

class QuoteListView(ListView):
    model = SmgQuotesTable

    def get_queryset(self):
        r_get = self.request.GET   # Get the data sendir by QuoteFormView
        query_filter = Quotes().planSelector(r_get['couple'], r_get['kids'], r_get['age']) # Use the filter to get the correct Quote
        queryset = super(QuoteListView, self).get_queryset().filter(composite=query_filter) # Aply the filter to get the correct queryset
        Quotes().salaryDiscount(queryset,r_get['salary'])  # Aply the discount of the salary

        return queryset
0 голосов
/ 03 апреля 2019

Вы также можете использовать обновление в наборе запросов или выполнить итерацию, как указано в dirkgroten

...