Допустим, у нас есть две модели: ModelA и ModelB.
Я буду использовать Django-Tables2 для создания таблицы из этих моделей.
В файле tables.py у вас может быть два отдельных класса таблиц (ниже).
from .models import ModelA, ModelB
import django_tables2 as tables
class ModelATable(tables.Table):
class Meta:
#some basic parameters
model = ModelA
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
class ModelBTable(tables.Table):
class Meta:
#some basic parameters
model = ModelB
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
Это означает, что будет таблица для каждой модели. Тем не менее, я думаю, что более эффективным решением для кодирования было бы следующее:
class MasterTable(tables.Table, request):
#where request is the HTML request
letter = request.user.letter
class Meta:
#getting the correct model by doing some variable formatting
temp_model = globals()[f'Model{letter}']
#some basic parameters
model = temp_model
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
Проблема заключается в передаче объекта запроса в определении таблицы из views.py. Это будет выглядеть примерно так:
def test_view(request):
#table decleration with the request object passed through...
table = MasterTable(ModelOutput.objects.all(), request)
RequestConfig(request).configure(table)
return render(request, 'some_html.html', {'table': table})
Я не знаю, как передать переменную, в данном случае объект запроса, в класс, чтобы можно было выполнить форматирование переменной.