Gabrielius B. Gabrielius B. - 4 months ago 36
Python Question

django-tables2 custom column

I'm working now on my first Django project. I want to render results table which contains all fields from Priekabos model and one custom column from Grafikas which should contain something similar to SELECT max(kada_moketi) FROM grafikas WHERE priekabos_id = ?. Whatever I try from examples nothing works. Should I write another view function with that custom query (Grafikas.objects.filter(priekabos_id=1) neither .aggregate(Max('kada_moketi') neither .latest('kada_moketi') worked for me) and make a new table class in which later PriekabosTable will inherit? That didn't work for me too.

Here's my code:

class Grafikas(models.Model):
id = models.AutoField(primary_key=True)
mokejimo_nr = models.IntegerField()
kada_moketi = models.DateField()
priekabos = models.ForeignKey('Priekabos', models.DO_NOTHING)

class Priekabos(models.Model):
id = models.AutoField(primary_key=True)
sutarties_nr = models.CharField(unique=True, max_length=45, verbose_name='Sut. Nr.')
nuomos_pradz = models.DateField()
sutarties_trukme = models.IntegerField()

def priekabos_table(request):
table = PriekabosTable(Priekabos.objects.all())
RequestConfig(request, paginate={'per_page': 20}).configure(table)
return render(request, 'isperkamoji_nuoma/priekabos_table.html', {'table': table})

class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz')

For better understanding, here's 'grafikas' table:
MySQL 'grafikas' table


It sounds like you might be able to fetch the extra field using annotate.

from django.db.models import Max
queryset = Priekabos.objects.annotate(max_kada_moketi=Max('grafikas__kada_moketi'))
table = PriekabosTable(queryset)

Remember to add the field to your table.

class PriekabosTable(tables.Table):
    class Meta:
        model = Priekabos
        attrs = {"class": "paleblue"}
        fields = ('id', 'sutarties_nr', 'nuomos_pradz', 'max_kada_moketi')