Not working (well) with @property fields

Issue #56 closed
Former user created an issue

This is something that I have found using properties to show a combinations of 2 fields, can't use str or unicode so I have create a property field on my Django model some like:

class Area(models.Model):
    name = models.CharField(max_length=100)
    short_name = models.CharField(max_length=10, unique=True)
    # Other fields

    def __str__(self):
        return '%s (%s)' % (self.name, self.short_name)

    @property
    def area(self):
        return '%s (%s)' % (self.name, self.short_name)

However, when I declare the BaseDatatableView, with:

    columns = ['area', 'other_field']

The JSON response looks ok, but, on view throws a "7. Warning: Ajax error", on terminal says:

django.core.exceptions.FieldError: Cannot resolve keyword 'area' into field. Choices are: name, short_name, [...]

If I add another field on the first place, it shows everything normal, but, repeats the first element at least twice.

Comments (3)

  1. Maciej Wisniowski repo owner

    There is no full traceback included so it is a bit hard to guess the exact location of this exception. I suppose that this is caused by order_columns (its definition is not shown in your samples). If you're using your property name within order_columns then it will fail as there is no 'area' field in the database.

    Anyway I'd suggest not using property but aggregate on your queryset, eg:

    from django.db import models
    from django.db.models import CharField, Value as V
    from django.db.models.functions import Concat
    
    qs = Area.objects.annotate(area=Concat(F('name), V(' ('), F('short_name'), V(')'), output_field=models.TextField())
    

    This way you'll have 'area' field that is filterable and orderable. See: https://docs.djangoproject.com/en/2.1/ref/models/database-functions/#concat

  2. Log in to comment