2

Technology Django 3.2

Model I have a model with fields with properties like max_length and decimal_places.

Part of the model, actual Product is inheriting from AbstractProduct:

class AbstractProduct(models.Model):
class Meta:
    abstract = True

PRODUCT_UNIT_CHOICES = [
    ('ml', 'milliliter'),
    ('g', 'gram'),
    ('st', 'stuks')
    ]
group = models.ForeignKey(ProductGroup,on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=255)
synonym = models.CharField(max_length=255,blank=True)
description = models.CharField(max_length=1024,blank=True)



def __str__(self):
    return '{} ({})'.format(self.name, self.pk)

View Furthermore I have a view returning a Queryset with model objects.

class ProductSearch(ListView):
    """
    Get searched Product objects from user
    """
    model = Product
    template_name = 'product_app/product_search.html'
    context_object_name = 'productlist'
    paginate_by = 24
    
    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = Product.objects.all()
        if query:
            object_list = object_list.filter(
                Q(name__icontains=query) | Q(synonym__contains=query)
            )
        return object_list

I would like to access the field attribute like so:

Template

{{ productlist.name.max_length }}
{{ productlist.name.field.max_length }}

also the following does not work:

{{ model_name.field_name.field.max_length }}
{{ model_name.field_name.field.decimal_places }}

and also the following does not work:

{{ productlist.model.field_name.field.max_length }}
{{ productlist.model.field_name.field.decimal_places }}

Any ideas? It seems to work with a model form, in which the latter examples work.

Thanks in advance.

Interestingly, using the shell, I can access the model field attributes using the expected object_list.model.name.field.max_length

Eric Muijs
  • 29
  • 6
  • So `model_name` is a `QuerySet`? – Willem Van Onsem Aug 14 '21 at 07:59
  • 1
    Does this answer your question? [How can I programmatically obtain the max\_length of a Django model field?](https://stackoverflow.com/questions/1829216/how-can-i-programmatically-obtain-the-max-length-of-a-django-model-field) – Sumithran Aug 14 '21 at 08:03

0 Answers0